Search code examples
vbacompiler-errorsinputbox

Input box Compile Error


I have been trying to get the name of a file name when someone uses this Macro. But for some reason every time I run the Macro I get the error: Compile error: Wrong number of arguments or invalid property assignment

I have looked at tons of videos and other responses but none of them have helped me deal with this error.

Sub inputbox()
Dim x As Variant
x = inputbox("Please enter your file name:", "File name")    
MsgBox ("Your file name is" & x) 
End Sub

Solution

  • Here is your procedure, corrected: (Copy & paste into a new module.)

    Option Explicit
    
    Sub MyInputBoxTest()
        Dim x As Variant
        x = inputbox("Please enter your file name:", "File name")
        MsgBox ("Your file name is " & x)
    End Sub
    

    Explanation:

    • Variant was misspelled. Note that since Variant is the default data type, you actually don't need to specify it. Dim x is the same as Dim x as Variant.

    • You can't use names like InputBox OR MsgBox as the name of your procedure. They are reserved words -- already used by another procedure built-in to VBA, so it confuses the compiler since it doesn't know which one you're referring to.

    • Added a space after the word is. (purely cosmetic)

    Functions like MsgBox and InputBox can be called different ways depending on whether you use brackets and whether you need to return a value.

    InputBox "Hi"
    InputBox ("Hi")
    

    ...either of these will run fine (but won't return the what the user enters.)

    Dim x
    x = InputBox ("Hi")
    

    ...will return the value to variable x, however:

    x = InputBox "Hi"
    

    ...will throw an error.


    It's highly recommended that, especially while learning, you add the line Option Explicit to the very top of every module. This will help "force" you to properly declare and refer to variables, objects, etc, by generating compile errors when you try to compile (F9) or run (F5) the code.