views:

497

answers:

2

In the following code, I get a compile time error because i is treated as a variant. The error is: "ByRef Argument type mismatch.".

But if I pass the parameters ByVal, there is no error why?

Private Sub Command2_Click()
    Dim i, j As Integer
    i = 5
    j = 7
    Call Swap(i, j)
End Sub

Public Sub Swap(ByRef X As Integer, ByRef Y As Integer)
    Dim tmp As Integer
    tmp = X
    X = Y
    Y = tmp
End Sub
+3  A: 

ByVal autoconverts the variant into a integer because it is passing a value. While the ByRef is attempting to pass a variable that you can modify in the subroutines. In essence I is X in the ByRef scenario. VB6 doesn't allow you to modify a variant as a integer.

RS Conley
+4  A: 

When you Dim several variables on a single line ie Dim i, j as Integer j is dimmed as an integer, but i is a variant. You need to declare each variable type explicitly. I prefer to include only a single variable per line.

Dim i As Integer, j As Integer

or

Dim i As Integer
Dim j As Integer

This is something I learned when I inherited another programmer's code

Beaner