用于检查a-z的字符串的函数

时间:2016-02-11 20:53:08

标签: excel vba function excel-vba

我想:

  • 循环显示特定列H(从H4开始)和
  • 对于该列中的每个单元格,调用一个函数来查看它是否为真(然后执行某些操作)或者是否为false(执行其他操作)。

我在***invalid use of property***上收到运行时错误Call Isletter

Sub IfBlank()

Dim Rng As Range
Dim MyCell As Range
Dim Isletter As Range

Set Rng = Range("H4:H" & Cells(Rows.Count, "H").End(xlUp).Row)

For Each MyCell In Rng
Call Isletter
If Isletter(MyCell.Value) = True Then
'do nothing
End If
If Isletter(MyCell.Value) = False Then
 MyCell.Value = "-"
 End If

 Next MyCell
End Sub

Public Function IsLetter(MyCell As String) As Boolean

    Dim intPos As Integer
    For intPos = 1 To Len(MyCell)
        Select Case Asc(Mid(MyCell, intPos, 1))
            Case 33 To 127
                Isletter = True
            Case Else
                Isletter = False
                Exit For
        End Select
    Next
End Function

3 个答案:

答案 0 :(得分:2)

IsLetter函数具有非可选参数(MyCell As String),因此您必须始终传递此参数并且必须是字符串。

If IsLetter(MyCell.Value) = True Then
  'do something
Else
  'do something else  
End If

答案 1 :(得分:2)

以下代码

  • 使用变量数组(比范围循环快得多)来处理来自H4的每个值:Hx
  • 使用可以快速检查字符串中是否至少有一个字符是字母。如果是那么空白那个字符串。

Thos行Range("H4:H" & Cells(Rows.Count, "H").End(xlUp).Row).Value2 = X将更改后的数组写回范围。

Sub IfBlank()

Dim rng1 As Range
Dim X
Dim lngCnt As Long

Dim objRegex As Object
X = Range("H4:H" & Cells(Rows.Count, "H").End(xlUp).Row).Value2

Set objRegex = CreateObject("vbscript.regexp")

    With objRegex
         .IgnoreCase = True
         .Pattern = "[a-z]"

         For lngCnt = 1 To UBound(X)
            If .test(X(lngCnt, 1)) Then X(lngCnt, 1) = vbNullString
         Next
    End With

Range("H4:H" & Cells(Rows.Count, "H").End(xlUp).Row).Value2 = X

End Sub

答案 2 :(得分:1)

“呼叫通讯”不应该在那里 代码的那部分应该是这样的

For Each MyCell In Rng
    If Isletter(MyCell.Value) = True Then
     'do nothing
    else
     MyCell.Value = "-"
    End If

Next MyCell

你的“IsLetter”功能会引起麻烦。 ASCII 127是“删除”

此外,只有ASCII 65-90和97 - 122是字母。这应该包括数字和特殊字符吗?

如果没有,那么它看起来应该更像这个

Public Function IsLetter(MyCell As String) As Boolean

Dim intPos As Integer
For intPos = 1 To Len(MyCell)
    Select Case Asc(Mid(Ucase(MyCell), intPos, 1))
        Case 90 To 122
            Isletter = True
            Exit Function
        Case Else
            Isletter = False
            Exit For
    End Select
Next
End Function