Geo*_*rge 20 excel vba excel-vba
我正在和VBA合作.我写了一个用户定义函数,它接受一个string
,处理它并返回一个清理过的string
.我不确定它有什么问题.我无法调用它并要求它处理我的字符串并将其返回.我在想我定义或返回它的方式有误.
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
Run Code Online (Sandbox Code Playgroud)
我像这样使用这个功能
Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)
Run Code Online (Sandbox Code Playgroud)
姓氏是一个字符串变量,通常看起来像这样Lastname*****
,我试图删除它背后的所有星星.让它在Lastname
没有星星的情况下返回.
Compile error: ByRef arugment type mismatch
当我试图运行时,我收到了.我在Windows 2003中使用Windows XP.
编辑:我添加了我的代码的基本结构,我有大约20行类似的代码.为我需要的每个领域做同样的事情.
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)
Run Code Online (Sandbox Code Playgroud)
Bat*_*eba 42
我怀疑你没有last_name
在呼叫者中正确设置.
随着声明 Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)
这只会last_name
在字符串中起作用,即
Dim last_name as String
Run Code Online (Sandbox Code Playgroud)
出现在呼叫者的某个地方.
原因是VBA 默认通过引用传递变量,这意味着数据类型必须在调用者和被调用者之间完全匹配.
1)强制ByVal - 更改函数以传递变量ByVal : Public Function ProcessString(ByVal input_string As String) As String
,或
2)Dim varname - Dim last_name As String
在使用之前放入调用者.
(1)因为for ByVal
,当传递给将强制转换为正确数据类型的函数时,会获取input_string的副本.它还可以提高程序的稳定性,因为函数无法修改调用者中的变量.
小智 10
我不知道为什么,但如果要将变量(作为变量)传递给其他过程或函数,则分别声明变量非常重要.
例如,有一个程序对数据进行一些操作:基于ID返回零件编号和数量信息.ID作为常量值,其他两个参数是变量.
Public Sub GetPNQty(ByVal ID As String, PartNumber As String, Quantity As Long)
Run Code Online (Sandbox Code Playgroud)
下一个主要代码给我一个"ByRef参数不匹配":
Sub KittingScan()
Dim BoxPN As String
Dim BoxQty, BoxKitQty As Long
Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty)
End sub
Run Code Online (Sandbox Code Playgroud)
而下一个也在运作:
Sub KittingScan()
Dim BoxPN As String
Dim BoxQty As Long
Dim BoxKitQty As Long
Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty)
End sub
Run Code Online (Sandbox Code Playgroud)