Excel VBA Dim 声明难题

标签 excel vba

我希望用户打开他们选择的文件来执行操作。我将变量 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/

相关文章:

windows - Perl Excel::Writer::XLSX-> new( 'myfile.xlsx' ) 在 Windows 8 环境中生成不适当的 I/O 错误

Excel 公式结果不是单元格值

c# - Excel 自动化 : Protect single worksheet from deletion by user

excel - 在 Excel 中取消注册 XLL (VBA)

vba - 如何开始使用 Visual Basic for Applications?

vba - 检测 Excel 上运行时添加的组合框上的事件

excel - 获取数据透视表中组总数的百分比

windows - 如何使用 VBA 执行 shell 命令?

excel - 如何在 Excel 中进行分布式计算

excel - 将分数视为 FALSE 的逻辑运算符