views:

261

answers:

2

In the following code, I get a compile time error:

ByRef Argument type mismatch.

But if I change the declaration of i,j to :

Dim i As Integer
Dim j As Integer

The error goes away. 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
+7  A: 

This is because when you do this in VB6:

Dim i, j As Integer

It reads to the compiler as

Dim i As Variant, j As Integer

Leading to your type mismatch. The answer is, as you said, to declare both with types, either as in your code:

Dim i As Integer
Dim j As Integer

Or on a single line, a la:

Dim i As Integer, j As Integer
John Rudy
+2  A: 

In VB 6, I is considered a variant, not an integer in the case you're describing.

Here's an article that describes the behavior.

Joseph