我希望用户打开他们选择的文件来执行操作。我将变量 File_path 指定为 Variant,因为我不知道它的类型是什么。我在代码中包含 Debug.Print TypeName(File_path) 来看看它给了我什么。我的代码是这样的:
Dim File_path As Variant
FilterType = "Text Files (*.txt),*.txt," & "Comma Separated Files (*.csv),*.csv," & "ASCII Files (*.asc),*.asc," & "All Files (*.*),*.*"
FilterIndex = 4
Title = "File to be Selected"
File_path = Application.GetOpenFilename(FileFilter:=FilterType, FilterIndex:=FilterIndex, Title:=Title)
If File_path = False Then
MsgBox "No file was selected."
Exit Sub
End If
Debug.Print TypeName(File_path)
Debug.Print 给我字符串。
但是当我重新运行代码时
Dim File_path As String
我收到运行时错误“13”:行中类型不匹配
If File_path = False Then
在这种情况下,正确的声明是什么?发现这一点的一般过程是什么?谢谢。
最佳答案
如果您想检查是否有任何字符串分配给您的变量,您需要通过以下方式之一执行此操作:
'1st option
if File_path = "" then
'2nd option- recommended
if Len(File_path) = 0 then
在这两种情况下,请将变量 File_path 保留为 String
。
关于Excel VBA Dim 声明难题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405993/