Byref argument type mismatch vba excel ошибка

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)

 

azma

Пользователь

Сообщений: 328
Регистрация: 03.12.2017

#1

29.06.2020 12:56:07

Добрый день, уважаемый форумчани!
ниже пользовательская функция, которая ругается на Ошибку: Compile error:  ByRef argument type mismatch

Код
Function GETLASTWORD(ByVal Text As String, Optional Separator As Variant)

Dim lastword As String

If IsMissing(Separator) Then
 Separator = " "
End If
lastword = StrReverse(Text)
lastword = Left(lastword, InStr(1, lastword, Separator, vbTextCompare))

GETLASTWORD = StrReverse(replace(lastword, Separator, ""))

End Function

как можно от этого избавиться?
функция в отделенной книге работает без проблем, а я добавил её в мою надстройку и начала ругаться.

Прикрепленные файлы

  • Screen Capture #001.png (41.66 КБ)

 

sokol92

Пользователь

Сообщений: 4456
Регистрация: 10.09.2017

Один из возможных вариантов — в Вашей надстройке переопределена функция Replace. Если это так, то подобного рода вещи (называть свои функции так же, как стандартные) не желательны. Замена в приведенном выше примере Replace на VBA.Replace может помочь.

 

azma

Пользователь

Сообщений: 328
Регистрация: 03.12.2017

sokol92, Спасибо большое!

 

Jerry.Sweer

Пользователь

Сообщений: 60
Регистрация: 11.01.2017

#4

21.10.2020 18:20:07

Друзья помогите с той же проблемой.
Ниже вписан код. При использовании в коде функции выдает ошибку «ByRef argument type mismatch»
Как лечить?

Благодарен заранее.

Код
Public Function Equalist(t1 As String, t2 As String) As Variant
    Dim h As Long, l As Long
        For h = Len(t1) To 1 Step -1
            For l = 1 To Len(t1) - h + 1
                If t2 Like "*" & Mid(t1, l, h) & "*" Then
                    If h > Equalist Then
                        Equalist = h
                        Exit Function
                    End If
                End If
            Next
        Next
End Function

____________________________________________________________­____________________________________________________________­__

Код
Public Sub Test4()


Dim i As Long, w As Long, ob As Long, LR As Long, c As Long
Dim Line1 As Object
Dim t As Single
Dim j As Worksheet
Dim NomerDokumenta As Integer, KodTovara As Integer, Naimenovanie As Integer, RaznicaKolvo _
As Integer, RaznicaGrn As Integer, Hozoperaciya As Integer

't = Timer

LR = Cells(Rows.Count, 1).End(xlUp).Row

ReDim B(1 To LR), D(1 To LR), E(1 To LR), R(1 To LR), S(1 To LR), U(1 To LR) As Variant

Set j = Sheets(3)

NomerDokumenta = j.Cells.Find("№ документа").Column
KodTovara = j.Cells.Find("Код товара").Column
Naimenovanie = j.Cells.Find("Наименование товара").Column
RaznicaKolvo = j.Cells.Find("Разница, кол-во").Column
RaznicaGrn = j.Cells.Find("Разница, грн").Column
Hozoperaciya = j.Cells.Find("Хоз.операция").Column

For c = 1 To 3
    ' Первый заход
    For i = 2 To LR
        B(i) = j.Cells(i, NomerDokumenta)
        D(i) = j.Cells(i, KodTovara)
        E(i) = j.Cells(i, Naimenovanie)
        R(i) = j.Cells(i, RaznicaKolvo)
        S(i) = j.Cells(i, RaznicaGrn)
        U(i) = j.Cells(i, Hozoperaciya)
    Next i
    
    For w = 2 To UBound(B())
        For i = 2 To UBound(B())
            If IsEmpty(j.Cells(w, 30)) And IsEmpty(j.Cells(i, 30)) Then
                If Equalist(E(w), E(i)) > 20 Then
                    If R(w) < 0 And R(i) > 0 Then
                        If Abs(j.Cells(w, 18)) > Abs(j.Cells(i, 18)) Then
                            If Abs(Abs(S(w) / R(w)) - Abs(S(i) / R(i))) < 20 Then
                                If w < i Then
                                    j.Rows(w + 1).Insert Shift:=xlDown
                                    j.Rows(w + 1).FillDown
                                    j.Cells(w + 1, 18) = -j.Cells(i + 1, 18)
                                    j.Cells(w, 18) = j.Cells(w, 18) + j.Cells(i + 1, 18)
                                    j.Cells(w + 1, 30) = "Четвертый круг 1_" & w
                                    j.Cells(i + 1, 30) = "Четвертый круг 1_" & w
                                        LR = Cells(Rows.Count, 1).End(xlUp).Row
                                            ReDim B(1 To LR), D(1 To LR), E(1 To LR), R(1 To LR), S(1 To LR), U(1 To LR) As Variant
                                                For ob = 2 To LR
                                                    B(ob) = j.Cells(ob, NomerDokumenta)
                                                    D(ob) = j.Cells(ob, KodTovara)
                                                    E(ob) = j.Cells(ob, Naimenovanie)
                                                    R(ob) = j.Cells(ob, RaznicaKolvo)
                                                    S(ob) = j.Cells(ob, RaznicaGrn)
                                                    U(ob) = j.Cells(ob, Hozoperaciya)
                                                Next ob
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        Next i
    Next w

End Sub

Изменено: Jerry.Sweer21.10.2020 22:40:40

 

Дмитрий(The_Prist) Щербаков

Пользователь

Сообщений: 14270
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#5

21.10.2020 18:37:08

Коды ОЧЕНЬ желательно оформлять соответствующим тегом(кнопка <…> в панели редактора сообщений). Без оформления тегами очень неудобно коды читать.
Ошибка банальная — у Вас массивы имеют тип VAriant, а функция Equalist требует тип String. Посему исправляется очень просто:

Код
If Equalist(Cstr(E(w)), Cstr(E(i))) > 20 Then

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Jerry.Sweer

Пользователь

Сообщений: 60
Регистрация: 11.01.2017

#6

21.10.2020 22:48:52

Спасибо большое.  

1014 / 118 / 2

Регистрация: 26.08.2011

Сообщений: 1,118

Записей в блоге: 2

1

04.04.2012, 23:44. Показов 41136. Ответов 4


Студворк — интернет-сервис помощи студентам

Работал достаточно долго с программой. Проверял элементы по отдельности. Делаю сборку программы — и вдруг на все переменные стали появляться такие сообщения. В чем может быть причина?



1



2785 / 717 / 106

Регистрация: 04.02.2011

Сообщений: 1,443

05.04.2012, 00:07

2

Не пишите программ без Option Explicit, пока не приучились к тому, что всякая переменная должна иметь свой тип. Каждому типу данных — свои операции, некоторые значения одних типов можно конвертировать в другой тип данных, например функции преобразования CInt, CDbl, CLng, CStr, CDate. Старайтесь следить, чтобы там где требуется определенный тип данных, данные были достоверно преобразованы в этот тип. Возможно у вас Sub или Function требует один тип, а вы подсовываете ей что-то неудобоваримое.



1



15137 / 6411 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

05.04.2012, 00:14

3

Цитата
Сообщение от AndreA SN
Посмотреть сообщение

вдруг на все переменные стали появляться такие сообщения

Не на все, а только на передаваемые в подпрограммы или функции.
В проекте, состоящем более чем из ~50 строк,

необходимо

использовать

Option Explicit

, о чем mc-black написал Вам в соседней теме. Поверьте, на написание операторов Dim Вы потратите меньше времени, чем на устранение «странных» ошибок.
Включите в Tools — Options — Editor опцию Require variables declaration, тогда Option Explicit будет появляться автоматически в

новых

модулях.



1



AndreA SN

1014 / 118 / 2

Регистрация: 26.08.2011

Сообщений: 1,118

Записей в блоге: 2

05.04.2012, 00:37

 [ТС]

4

дело в том, что я уже работаю с Option Explicit
Но оказалось, что объявление переменных вида

Visual Basic
1
 Dim i, j As Integer

считает пременную i типом Variant !!!
Стал писать

Visual Basic
1
Dim i As Integer, j As Integer

— ошибки пропали.
Или я тут что-то лишнее придумал?



1



15137 / 6411 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

05.04.2012, 00:42

5

Цитата
Сообщение от AndreA SN
Посмотреть сообщение

объявление переменных вида
Dim i, j As Integer
считает пременную i типом Variant !

Именно так. В окне Locals в режиме останова это хорошо видно.



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

05.04.2012, 00:42

5

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.byref argument type mismatch

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.ByRef Argument Type Mismatch Causes

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:

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

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:

Private Sub CommandButton2_Click()

‘ 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:

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 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:

Private Sub View_Report_Click()

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:

Sub KittingScan()

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:

Sub KittingScan()

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.Changing the Inputs to Work With Option Explicit

The following example provides the solution:

Option Explicit

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

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

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

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.

    [!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]

Возможно, вам также будет интересно:

  • Bwsb 51051 коды ошибок
  • Bwsa 51051 коды ошибок
  • Bwe ошибка на скании что это значит
  • Busybox ошибка при загрузке
  • Busy домофон элтис ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии