1

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 does choose a file, this If statement creates an error. Can anyone tell me the proper way to accomplish this?

1
  • If you would have pressed the magic key F1 in Excel you would have got your answer :) Commented Aug 14, 2012 at 15:28

3 Answers 3

3

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

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

If fn = "False" Then

(changed explanation - thanks @SiddharthRout)

8 Comments

Application.GetOpenFilename returns a variant
@siddharthRout: changed explanation of what happens in FancyCorndog's code
Sean. I don't mean to be picky but this statement The function does not return the boolean False, but the string "False" is incorrect :( When nothing is selected it does return a boolean else it returns a string and that is the reason why we declare the variable fn as variant.
@SiddharthRout, the function as written will cause the return value to be cast into a string. The test of "False"=False evaluates as true, so the test works on a cancel, but fails when comparing anything other than a string that can be interpreted as a boolean
I am not saying that your method is incorrect. I am just saying that the statement he function does not return the boolean False, but the string "False" is incorrect. It does return a boolen in case of Cancel which can be converted to a "String" like you have done :)
|
1

Change

If fn = False Then

To

If CStr(fn) = "False" Then

2 Comments

Why do you coerce a string to a string? Just write If fn = "False" Then
@Jean-FrançoisCorbett. Thanks. Good point. When I was playing with it, I didn't test that out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.