Excel VBA 打开文件(错误处理)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11955315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 17:17:48  来源:igfitidea点击:

Excel VBA Open File (error handling)

excelvbaexcel-vba

提问by Neat Machine

I'm trying to account for a case when the user does not find a file to open:

我正在尝试解决用户找不到要打开的文件的情况:

Dim fn As String
fn = Application.GetOpenFilename("All Files,.", 1, "Select a file", , False)

If fn = False Then
    Exit Sub
End If

This does what I want it to when a file is not chosen.

当未选择文件时,这会执行我想要的操作。

But when the user doeschoose a file, this If statement creates an error. Can anyone tell me the proper way to accomplish this?

但是当用户确实选择了一个文件时,这个 If 语句会产生一个错误。谁能告诉我实现这一目标的正确方法?

回答by Siddharth Rout

If you check Excel's inbuilt help, you will notice that Application.GetOpenFilenamereturns a variant. So all you have to do is declare fnas Variant,

如果您查看 Excel 的内置帮助,您会注意到它Application.GetOpenFilename返回了一个变体。所以你所要做的就是声明fnVariant

Sub Sample()
    Dim fn As Variant

    fn = Application.GetOpenFilename("All Files,.", 1, "Select a file", , False)

    If fn = False Then Exit Sub

    MsgBox fn
End Sub

回答by SeanC

The function does not return the boolean False, but the string"False", as it will cast the variant from the function into your variable type, so your test should be

该函数不返回 boolean False,而是string"False",因为它将变量从函数转换为您的变量类型,因此您的测试应该是

If fn = "False" Then

(changed explanation - thanks @SiddharthRout)

(更改了解释-感谢@SiddharthRout)

回答by Scott Holtzman

Change

改变

If fn = False Then

To

If CStr(fn) = "False" Then