我希望用户打开自己选择的文件以进行处理。我将变量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给了我String。

但是当我重新运行代码时

 Dim File_path As String


我收到运行时错误“ 13”:在行上键入不匹配项

 If File_path = False Then


在这种情况下正确的声明是什么,发现它的一般过程是什么?谢谢。

最佳答案

您实际上应该将返回值声明为变体

Dim File_path As Variant




出现错误的原因是Application.GetOpenFileName返回Variant。当该值可以转换为可以的字符串,但是当用户单击“取消”或X按钮时,将返回Boolean,并且不能直接与String类型进行比较。

为了演示这一点,您可以运行以下代码。如果单击“取消”,则不会出现错误。如果选择文件,则会收到与收到的相同的Type Mismatch错误,但原因相反。尝试将String分配给Boolean类型。

Dim ans As Boolean
ans = Application.GetOpenFilename()


如果您查看Microsoft Documentation,它在其中的用法就很好解释了。

07-25 23:22
查看更多