VBA UDF上的“ByRef参数types不匹配”错误
这是提供问题的function:
它应该检查一个string是否只有数字0-9
Public Function onlyNumbers(str As String) For i = 1 To Len(str) If Not (IsNumber(Mid(str, i, 1))) Then onlyNumbers = False End If Next onlyNumbers = True End Function
模块:
Dim value as string For j = 2 to 2205 value = Cells(j, 2) value = Trim(Replace(Replace(value, "-", ""), ".", "")) 'Error gives on the if check (it highlights "value") : If onlyNumbers(value) Then ' code goes on... no syntax error, execution only
只是为了节省所有的麻烦 – 你甚至不需要一个函数或循环,只需使用Like
运算符:
Dim myString As String myString = "12345" If myString Like Application.Rept("[0-9]", Len(myString) Then MsgBox "myString is numbers only" Else MsgBox "myString contains other characters that aren't 0-9" End If
如果你真的希望这是一个function,那么:
Function IsNumbersOnly(str As String) As Boolean IsNumbersOnly = str Like Application.Rept("[0-9]", Len(str)) End Function
加:
Dim value As String
在小组的开始。
看来人们在评论中给出了很好的build议,下面是一个工作的解决scheme,它接受并减less了代码库。
Public Function onlyNumbers(ByVal str As String) As Boolean For i = 1 To Len(str) If Not (IsNumeric(Mid(str, i, 1))) Then Exit Function Next onlyNumbers = True End Function
Cells()返回一个范围对象。
您需要将值设置为范围的值。 调用函数时试试Cells()。的值。
value = Cells(j, 2) value = Trim(Replace(Replace(value, "-", ""), ".", "")) 'Error gives on the if check : If onlyNumbers(value.value) Then
4错误
1)按照@ScottCraner的指示退出正确逻辑的循环
2)vba已经使用了variables名“value”,可能与@ScottCrane指出的冲突(问题标题错误)
3)接下来我错过了
4)IsNumber不在VBA中,正确的是@ScottCraner所指的IsNumeric
Public Function onlyNumbers(str As String) For i = 1 To Len(str) If Not (IsNumeric(Mid(str, i, 1))) Then Exit Function End If Next i onlyNumbers = True End Function
感谢所有帮助过的人
我相信你的单元电话有问题。 请将其更改为Cells(2,10)。 这将是j2,因为这个API是单元格(行,列)按索引
Dim Value As String Value = Cells(2, 10) Value = Trim(Replace(Replace(Value, "-", ""), ".", "")) Debug.Print onlyNumbers(Value)
而你的另一块有一些不正确的语法,因为你应该使用IsNumeric
Public Function onlyNumbers(str As String) For i = 1 To Len(str) If Not IsNumeric(Mid(str, i, 1)) Then onlyNumbers = False End If Next onlyNumbers = True End Function