我想用一个按钮导入一个txt文件到excel中,我有一个对话框来选择一个文件夹名称,并显示用户选择的文件夹名称。
如果用户选择取消,会因为类型不匹配而发生错误。我已经声明变量为VARIANT
请看一下代码。
Sub ImportTXTFiles()
Dim fso As Object
Dim xlsheet As Worksheet
Dim qt As QueryTable
Dim txtfilesToOpen As Variant, txtfile As Variant
Application.ScreenUpdating = False
Set fso = CreateObject("Scripting.FileSystemObject")
txtfilesToOpen = Application.GetOpenFilename(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If txtfilesToOpen = "False" Then
Exit Sub
End If
For Each txtfile In txtfilesToOpen
' FINDS EXISTING WORKSHEET
For Each xlsheet In ThisWorkbook.Worksheets
If xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "") Then
xlsheet.Activate
GoTo ImportData
End If
Next xlsheet
' CREATES NEW WORKSHEET IF NOT FOUND
Set xlsheet = ThisWorkbook.Worksheets.Add( _
After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "")
xlsheet.Activate
GoTo ImportData
我的问题是,如何处理这个异常?
If txtfilesToOpen = "False" Then
Exit Sub
End If
如果用户取消选择,而变量被声明为变量。
先谢谢你了。
也许使用这个辅助功能会帮助你。
Option Explicit
Sub Test()
Dim txtfilesToOpen As String
txtfilesToOpen = GetFile
End Sub
Private Function GetFile() As String
Dim fldr As FileDialog
Set fldr = Application.FileDialog(msoFileDialogFilePicker)
With fldr
.Title = "Text Files to Open"
.AllowMultiSelect = False
If .Show <> -1 Then
MsgBox "No file was picked. Please run the macro again."
End
End If
GetFile = .SelectedItems(1)
End With
End Function
如果用户没有选择文件,一个MsgBox将弹出警告用户,然后完成整个过程。注意,这个过程一次只对一个被选中的项目有效。如果你需要选择多个,可以考虑使用文件夹选择器。