关于Like运算符的使用 分类:ExcelVBA>>VBA语法
引子 公司要求按照已经用Excel制作好的固定的格式上交报表,很简单,不一会就完成并上交了,结果,没多久报表被退回,原因是报表中有些单元格中的字符数超过了规定的100个,只好重做。当时,首先想到的问题就是如何知道单元格中的字符数,这可用Excel所提供的Len工作簿函数简单的完成。事后又仔细思考了一下,在Word中有字数统计功能,但在Excel中没有,能否摸仿Word中的字数统计功能,对Excel中的单元格或者所选的单元格区域进行字数统计呢?进一步说,将单元格或者所选的单元格区域中的汉字、数字、字母等进行分类统计。当然,这些都可使用工作簿函数实现,下面所讲解的内容是使用VBA来实现上述功能。
在Excel中实现字数统计 (1) 使用Len工作簿函数进行简单的字数统计 ‘① - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - '对当前单元格进行字数统计 Sub TotalCellCharNum() Dim i As Long i = Len(ActiveCell.Value) MsgBox "当前单元格的字数为:" & Chr(10) & i End Sub ‘② - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - '对所选的单元格区域进行字数统计 Sub TotalSelectionCharNum() Dim i As Long Dim rng As Range For Each rng In Selection i = i + Len(rng.Value) Next rng MsgBox "所选单元格区域的字数为:" & Chr(10) & i End Sub
(2) 使用Like运算符进行较复杂的字数统计 ‘③ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - '对当前单元格中的文本分类进行字数统计 Sub SubTotalCellCharNum() Dim str As String, ChineseChar As Long Dim Alphabetic As Long, Number As Long Dim i As Long, j As Long j = Len(ActiveCell.Value) For i = 1 To Len(ActiveCell) str = Mid(ActiveCell.Value, i, 1) If str Like "[一-龥]" = True Then ChineseChar = ChineseChar + 1 '汉字累加 ElseIf str Like "[a-zA-Z]" = True Then Alphabetic = Alphabetic + 1 '字母累加 ElseIf str Like "[0-9]" = True Then Number = Number + 1 '数字累加 End If Next MsgBox "当前单元格中共有字数" & j & "个,其中:" & vbCrLf & "汉字:" & ChineseChar & "个" & _ vbCrLf & "字母:" & Alphabetic & "个" & _ vbCrLf & "数字:" & Number & "个", vbInformation, "文本分类统计" End Sub ‘④ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - '对所选的单元格区域中的文本分类进行字数统计 Sub SubTotalSelectionCharNum() Dim str As String, ChineseChar As Long Dim Alphabetic As Long, Number As Long Dim i As Long, rng As Range, j As Long For Each rng In Selection j = j + Len(rng.Value) For i = 1 To Len(rng) str = Mid(rng.Value, i, 1) If str Like "[一-龥]" = True Then ChineseChar = ChineseChar + 1 '汉字累加 ElseIf str Like "[a-zA-Z]" = True Then Alphabetic = Alphabetic + 1 '字母累加 ElseIf str Like "[0-9]" = True Then Number = Number + 1 '数字累加 End If Next Next MsgBox "所选单元格区域中共有字数" & j & "个,其中:" & vbCrLf & "汉字:" & ChineseChar & "个" & _ vbCrLf & "字母:" & Alphabetic & "个" & _ vbCrLf & "数字:" & Number & "个", vbInformation, "文本分类统计" End Sub 在这里使用了Like运算符实现指定字符的查找,效果图01所示。
O7cxhxzO.rar
(9.07 KB, 下载次数: 325)
|