Leggere in inglese Modifica

Condividi tramite


ByRef argument type mismatch

An argument passed ByRef (by reference), the default, must have the precise data type expected in the procedure. This error has the following cause and solution:

  • You passed an argument of one type that could not be coerced to the type expected.

    For example, this error occurs if you try to pass an Integer variable when a Long is expected. If you want coercion to occur, even if it causes information to be lost, you can pass the argument in its own set of parentheses.

    For example, to pass the Variant argument MyVar to a procedure that expects an Integer argument, you can write the call as follows:

      Dim MyVar 
      MyVar = 3.1415 
      Call SomeSub((MyVar)) 
    
      Sub SomeSub (MyNum As Integer) 
      MyNum = MyNum + MyNum 
      End Sub
    

    Placing the argument in its own set of parentheses forces evaluation of it as an expression. During this evaluation, the fractional portion of the number is rounded (not truncated) to make it conform to the expected argument type. The result of the evaluation is placed in a temporary location, and a reference to the temporary location is received by the procedure. Thus, the original MyVar retains its value.

    Nota

    If you don't specify a type for a variable, the variable receives the default type, Variant. This isn't always obvious. For example, the following code declares two variables, the first, MyVar, is a Variant; the second, AnotherVar, is an Integer.

     Dim MyVar, AnotherVar As Integer 
    

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.