这是给出问题的功能:
它应该检查字符串是否只有数字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
答案 0 :(得分:3)
只是为了节省所有麻烦 - 你甚至不需要函数或循环,只需使用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 IsNumbersOnly(str As String) As Boolean
IsNumbersOnly = str Like Application.Rept("[0-9]", Len(str))
End Function
答案 1 :(得分:1)
添加:
Dim value As String
在Sub。
的开头答案 2 :(得分:1)
看来人们在评论中给出了很好的建议,下面是一个有效的解决方案,可以接受它们并减少代码库。
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
答案 3 :(得分:0)
Cells()返回一个范围对象。
您需要将值设置为范围的值。在调用函数时尝试使用Cells()。值。
value = Cells(j, 2)
value = Trim(Replace(Replace(value, "-", ""), ".", ""))
'Error gives on the if check :
If onlyNumbers(value.value) Then
答案 4 :(得分:0)
4个错误
1)退出循环以获得@ScottCraner指出的正确逻辑
2)变量名称"值"已被vba使用,可能与@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
感谢所有帮助过的人
答案 5 :(得分:-1)
我相信你的Cell调用有问题。请将其更改为单元格(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