I’m working with VBA. I wrote a user define function that takes a string
, process it and return a cleaned string
. I am not sure what is wrong with it. I am not able to call it and ask it to process my string and return it. I am thinking there are a mistake in the way I am defining or returning it.
Public Function ProcessString(input_string As String) As String
' The temp string used throughout the function
Dim temp_string As String
For i = 1 To Len(input_string)
temp_string = Mid(input_string, i, 1)
If temp_string Like "[A-Z, a-z, 0-9, :, -]" Then
return_string = return_string & temp_string
End If
Next i
return_string = Mid(return_string, 1, (Len(return_string) - 1))
ProcessString = return_string & ", "
End Function
And I use this function like this
Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)
Last name is a string variable, usually looks like this Lastname*****
, and I am trying to remove all the stars behind it. Have it return Lastname
without the stars.
I received Compile error: ByRef arugment type mismatch
when I tried to run this. I am using Windows XP with Office 2003.
EDIT: I added the basic struction of the code I have, I have about 20 lines of the similar code. Doing the same thing for each field I need.
Private Sub CommandButton2_Click()
' In my original production code I have a chain of these
' Like this Dim last_name, first_name, street, apt, city, state, zip As String
Dim last_name As String
' I get the last name from a fixed position of my file. Because I am
' processing it from another source which I copied and pasted into excel
last_name = Mid(Range("A4").Value, 20, 13)
' Insert the data into the corresponding fields in the database worksheet
Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)
The ByRef argument type mismatch VB6 code exception usually happens in MS Excel VBA due to different variables passing two ByRef arguments. As a result, your system throws the java.lang.illegalargumentexception: argument type mismatch, and halts further procedures, which are critical for your type mismatch project or application.
Unfortunately, we confirmed a similar type mismatch error when your script’s data types have different variables, although the argument type is identical. So, you are at the best place to learn how to overcome the byref argument type mismatch date error using real-life examples and debugging approaches that apply to all applications and data-type projects.
Contents
- Why Is the ByRef Argument Type Mismatch Error Happening?
- – Creating a User Define Function With a String
- – Creating View Reports With Invalid Arguments
- How To Fix the ByRef Argument Type Mismatch Code Exception?
- – Changing the Inputs to Work With Option Explicit
- Conclusion
Why Is the ByRef Argument Type Mismatch Error Happening?
The compile error ByRef argument type mismatch VBA usually happens in MS Excel due to different variables passing two ByRef argument types. In addition, we confirmed a similar mismatch error when the data types in your project have different variables, halting your code and failing all procedures.
So, the ByRef argument type mismatch workbook code exception likely affects MS Excel VBA projects due to different variable names. For instance, although advanced syntaxes allow launching operations with other variable names, passing two procedures confuses your program and establishes the argument type mismatch bug.
As a result, we suggest compiling the inputs and main processes separately to avoid this mistake and pasting them to a single Excel VBA document only after ensuring all snippets are functional. Still, due to its dynamic trait, this procedure does not guarantee to prevent the ByRef argument type mismatch worksheet error.
On the flip side, your program will encounter the ByRef argument type mismatch range exception when your data types have different variables. For example, the data types we assign to the project confuse the program and prevent further code alterations, although the variable names are identical.
As you can tell, this annoying code exception has different culprits, making troubleshooting the program and pinpointing the failed input challenging. Still, we wrote several chapters recreating the VBA ByRef argument type mismatch integer error before listing the most sophisticated solutions and debugging procedures.
– Creating a User Define Function With a String
This guide’s first broken VBA example attempts to create a user-defined function with a string. In addition, the program should take the string, process the inputs, and return a cleaned procedure.
Unfortunately, this is not the case because the script prevents you from calling it and asking for refined input. As a result, we will show you the complete code snippet and the public function creating the basic structure.
You can learn more about this example in the following code:
‘ The temp string used throughout the function
Dim temp_string As String
For i = 1 To Len (input_string)
temp_string = Mid (input_string, i, 1)
If temp_string Like “[A-Z, a-z, 0-9, :, -]” Then
return_string = return_string & temp_string
End If
Next i
return_string = Mid (return_string, 1, (Len (return_string) – 1))
ProcessString = return_string & “, ”
End Function
The last code line confirms where the function ends.
Still, the following example helps you learn about the worksheets that initiate the former syntax:
Worksheets (data_sheet) .Range (“C2”).Value = ProcessString (last_name)
Lastly, we will provide the process we launch for each procedure.
These inputs should help you learn about the property confusing the system, as shown below:
‘ Like this Dim last_name, first_name, street, apt, city, state, zip As String
Dim last_name As String
last_name = Mid (Range (“A4”) .Value, 20, 13)
‘ Insert the data into the corresponding fields in the database worksheet
Worksheets (data_sheet) .Range (“C2”) .Value = ProcessString (last_name)
This code snippet completes the first broken instance that blocks your application.
– Creating View Reports With Invalid Arguments
Another typical instance is launching this code exception and halting further procedures when attempting to create view reports with invalid arguments. However, as the former chapters explain, doing this is incorrect because the program fails to interpret the inputs with different data types. As a result, we will show you two code snippets recreating the error and displaying the broken exception. Namely, the first instance calls the primary public function, and the second example develops the sub-view report.
The following example provides the incorrect argument and an integer variable:
Dim amount As Integer
amount = 80
Call processAmt (amount)
‘Rest of the code
End Sub
Public Function processAmt (amount As Long)
‘Do your processing and calculations here
End Function
Unfortunately, the program displays a compile warning confirming your project’s inconsistencies and flaws. However, this section is only complete with the private sub-view report because it explains the project’s functions and purposes.
You can learn more about this script in the following example:
Dim blRet As Boolean
Dim fileName, Report, msg1 As String
Report = “rptInvoice”
fileName = “C: Invoices PDF Files” & Replace (Date, “/”, “”) & “.pdf”
DoCmd.OpenReport Report, acViewPreview
blRet = ConvertReportToPDF (Report, vbNullString, fileName, False, True, 1, “”, “”, 0, 0)
DoCmd.Close acReport, Report
sbSendreturnform fileName
End Sub
Although we could include other inputs and functions in this code snippet, we kept the example as short as possible while launching the exception and blocking the project. In addition, remember your document likely has a different output, but this does not change the debugging approaches.
How To Fix the ByRef Argument Type Mismatch Code Exception?
You can fix the ByRef argument type code exception by declaring the variables in different places to pass their properties into other functions or procedures. Fortunately, you can also improve your application by making the data types identical or ensuring the variable names in all procedures are similar.
As you can tell, although pinpointing the culprits and troubleshooting your program is challenging, several debugging approaches that resolve the error exist. Hence, declaring the variables separately to pass them into other functions is the best debugging procedure because it does not affect other elements and commands.
For your convenience, we will exemplify the critical code alterations you must make to your application to overcome the mistake. So, this example manipulates the ID’s part number and quantity information as constant values.
The following example helps you learn about the main command line:
Public Sub GetPNQty (ByVal ID As String, PartNumber As String, Quantity As Long)
Launching this procedure in a snippet without a quantity element confuses your program.
For example, this code snippet reproduces the ByRef code exception because it lacks the vital command:
Dim BoxPN As String
Dim BoxQty, BoxKitQty As Long
Call GetPNQty (InputBox (“Enter ID:”), BoxPN, BoxQty)
End sub
On the contrary, your application faces no issues running the following script because it contains the quantity element, as shown below:
Dim BoxPN As String
Dim BoxQty As Long
Dim BoxKitQty As Long
Call GetPNQty (InputBox (“Enter ID:”), BoxPN, BoxQty)
End sub
Still, remember to implement this solution to all failed snippets and functions.
– Changing the Inputs to Work With Option Explicit
You can reenable your program by changing the inputs to work with the explicit option property. By doing this, you will be able to debug the script and flatten any inconsistencies. You can introduce this command line at the beginning.
The following example provides the solution:
Public Function ProcessString(input_string As String) As String
‘ The temp string used throughout the function
Dim temp_string As String
Dim i As Integer ‘ This is new
Dim return_string As String ‘ This is new
For i = 1 To Len(input_string)
temp_string = Mid(input_string, i, 1)
If temp_string Like “[A-Z, a-z, 0-9, :, -]” Then
return_string = return_string & temp_string
End If
return_string = Mid(return_string, 1, (Len(return_string) – 1))
ProcessString = return_string & “, ”
End Function
You can reuse this code snippet in your document, but changing the values and elements is critical to match your project’s needs.
Conclusion
The ByRef argument type mismatch code exception happens in Excel VBA due to different variables passing two arguments. Still, the following list helps you remember the details before fixing your script:
- We confirmed the error when your script’s data types have different variables
- The first debugging approach declares the variables in different places to pass their properties
- You can also debug the program by changing the inputs to work with the explicit option property
After applying our debugging methods and solutions, you will again enjoy working on your Excel VBA project. Still, you must carefully replicate the scripts to avoid other complications and errors.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
azma Пользователь Сообщений: 328 |
#1 29.06.2020 12:56:07 Добрый день, уважаемый форумчани!
как можно от этого избавиться? Прикрепленные файлы
|
||
sokol92 Пользователь Сообщений: 4456 |
Один из возможных вариантов — в Вашей надстройке переопределена функция Replace. Если это так, то подобного рода вещи (называть свои функции так же, как стандартные) не желательны. Замена в приведенном выше примере Replace на VBA.Replace может помочь. |
azma Пользователь Сообщений: 328 |
sokol92, Спасибо большое! |
Jerry.Sweer Пользователь Сообщений: 60 |
#4 21.10.2020 18:20:07 Друзья помогите с той же проблемой. Благодарен заранее.
__________________________________________________________________________________________________________________________
Изменено: Jerry.Sweer — 21.10.2020 22:40:40 |
||||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
#5 21.10.2020 18:37:08 Коды ОЧЕНЬ желательно оформлять соответствующим тегом(кнопка <…> в панели редактора сообщений). Без оформления тегами очень неудобно коды читать.
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
Jerry.Sweer Пользователь Сообщений: 60 |
#6 21.10.2020 22:48:52 Спасибо большое. |
In this article, we will look at the ByRef argument type mismatch error. First, let us have a look at what is ByRef and the difference between ByRef and ByVal.
In Visual Basic, you can pass an argument to a procedure or function by value or by reference. This is known as the passing mechanism, and it determines whether the procedure or function can modify the variable that has been passed. The declaration of the function determines the passing mechanism for each parameter by specifying the ByVal or ByRef keyword.
The advantage of passing an argument ByRef is that the procedure can return a value to the calling code through that argument. The advantage of passing an argument ByVal is that it protects a variable from being changed by the procedure. The default in VBA is to pass arguments by reference. For more details, you can refer to the article here.
Whenever an argument is passed ByRef (by reference), the default, you must match the precise data type in the argument passed and the argument in the function definition. So, let us have a look at some of the most likely causes of the error and how to fix them:
Case 1: You passed an argument of one type that could not be forced to the type expected.
For example, this error occurs if you try to pass an Integer variable when a Long is expected.
Sub callByRef() Dim amount As Integer amount = 80 Call processAmt(amount) 'Rest of the code End Sub Public Function processAmt(amount As Long) 'Do your processing here End FunctionThe error that you will get is:
Let us look at possible solutions to this:
Solution 1:
If possible, always try to match the data type. This is easiest and quickest solution. So, in our case, the amount variable should be integer (or long, based on the requirement) in both the places.
Dim amount As LongSolution 2:
Force coercion to occur by passing the argument in its own set of parentheses (even if it causes information to be lost).
Sub callByRef() Dim amount As Integer amount = 80 Call processAmt((amount)) End SubPlacing the argument in its own set of parentheses the fractional portion of the number is rounded to make it conform to the expected argument type. The result of the evaluation is placed in a temporary location and the original amount retains its value.
Solution 3:
Similar to the above solution, you can explicitly convert the data type of the variable while passing
Sub callByRef() Dim amount As Integer amount = 80 Call processAmt(CLng(amount)) End SubSolution 4:
Pass the variable by value. For that, specify the keyword “ByVal” before the variable name in the function definition.
Public Function processAmt(ByVal amount As Long) 'Do your processing here End FunctionCase 2: You have not declared the variable in the calling sub.
Sub callByRef() amount = 80 Call processAmt(amount) End Sub Public Function processAmt(amount As Long) 'Do your processing here End FunctionHere you need to make sure that the variable is defined along with the data type
Dim amount As LongAs a standard practice, you should always have “Option Explicit” added to your code as the first line. This makes declaring variables mandatory and helps preventing many errors. Here is an example of where to place it
Option Explicit Sub callByRef() 'Code here End SubCase 3: Variable is declared but the data type is not specified
Dim firstNameIn VB, if you declare a variable without specifying the data type, by default the variable is assigned the type “variant”. So, you need to explicitly specify the variable data type before passing it to a function.
Another common source of error here is when you declare multiple variables on a single line and specify the data type only for the last one. For example,
Dim firstName, lastName As StringHere, VBA sets lastName as a String. However, for firstName it is a variant data type and not String. This is because in VBA, you have to specify data type for each and every variable separately (even if the variables are declared on the same line).
So, the above statement is equivalent to:
Dim firstName As Variant, lastName As StringAnd the right way to declare the variable is
Dim firstName As String, lastName As StringSo, to summarize, the argument data type should always be same while calling a function and in the function definition. If you get this error, you can fix it by using one of following methods
- Make sure the variable is defined with correct data type
- Use explicit conversion while passing the argument
- Use an own set of parentheses while passing the argument
- Pass the variable by value if you do not intend to change the value in the called function
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
ByRef argument type mismatch |
vblr6.chm1011308 |
vblr6.chm1011308 |
office |
6adca657-8620-e3f1-3587-e317f988979c |
06/08/2017 |
high |
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.[!NOTE]
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).
[!includeSupport and feedback]