How to Avoid the "ByRef Argument Type Mismatch" Error
This article was previously published under Q138535
This article has been archived. It is offered "as is" and will no longer be updated.
If you pass a parameter to a function or sub procedure by reference, thetype of the actual parameter passed and the corresponding function argumentmust match. Otherwise, you will get a "ByRef argument type mismatch" error.
The reason types have to match with ByRef parameters is that the calledprocedure is working on the original outside variable through a referencepointer. In the following step-by-step example, if the procedure thinks itis modifying a variant but the outside variable is really a control, thedata will probably be ruined.
If something is passed by value, Visual Basic can do automatic typeconversion. When you pass by value, the inside procedure is working on acopy and can therefore modify it in any way, such as converting the passedobject to a temporary Variant and working on that.
This applies to simple built-in types as well as objects. Problems likethis are easier to understand and debug if you set Option Explicit anddeclare every variable type explicitly.
- Start a new project in Visual Basic. Form1 is created by default.
- Add the following code to the General Declarations section of Form1:
Sub test(x As Control) x.Text = "hello" End Sub
- Add the following code to the Form_Click event of Form1:
Private Sub Form_Click() For Each object In Controls test object Next End Sub
- Press F5 to run the program. Click Form1. The "ByRef argument type mismatch" error appears because the type of object passed is a Variant by default and the argument to test() is of type Control.
- To avoid this error, you can do one of the following:
- Pass the control ByVal:-or-
Sub test(ByVal x As Control) x.Text = "hello" End Sub
- Dimension the object as a Control variable so that the types match:
Private Sub Form_Click() Dim object As Control For Each object In Controls test object Next End Sub
- Pass the control ByVal:
3.00 4.00 vb4win vb4all
Article ID: 138535 - Last Review: 12/04/2015 12:13:12 - Revision: 1.1
Microsoft Visual Basic 4.0 Standard Edition, Microsoft Visual Basic 4.0 Professional Edition, Microsoft Visual Basic 4.0 Professional Edition, Microsoft Visual Basic 4.0 16-bit Enterprise Edition, Microsoft Visual Basic 4.0 32-Bit Enterprise Edition, Microsoft Visual Basic 3.0 Professional Edition, Microsoft Visual Basic 3.0 Professional Edition
- kbnosurvey kbarchive KB138535