excel - 我需要一种算法来计算 Excel VBA 中以字母“a”和“A”开头的 M 列中的单词数
问题描述
在这里,我的代码只计算单词的数量,但我不知道该怎么做才能计算出 M 列中以字母“A”和“a”开头的单词
Sub CountWords()
Dim xRg As Range
Dim xRgEach As Range
Dim xAddress As String
Dim xRgVal As String
Dim xRgNum As Long
Dim xNum As Long
On Error Resume Next
xAddress = ActiveWindow.RangeSelection.Address
Set xRg = Application.InputBox("Introduceti diapazonul:", "Selectare", xAddress, , , , , 8)
If xRg Is Nothing Then Exit Sub
Application.ScreenUpdating = False
If Application.WorksheetFunction.CountBlank(xRg) = xRg.Count Then
MsgBox "Numarul de cuvinte este: 0", vbInformation, ""
Exit Sub
End If
For Each xRgEach In xRg
xRgVal = xRgEach.Value
xRgVal = Application.WorksheetFunction.Trim(xRgVal)
If xRgEach.Value <> "" Then
xNum = Len(xRgVal) - Len(Replace(xRgVal, " ", "")) + 1
xRgNum = xRgNum + xNum
End If
Next xRgEach
MsgBox "Numarul de cuvinte: " & Format(xRgNum, "#,##0"), vbOKOnly, "Raspuns"
Application.ScreenUpdating = True
End Sub
解决方案
假设每个单元格包含一个单词,请使用:
Sub ACount()
Dim i As Long, N As Long, Kount As Long
Dim ch As String
Kount = 0
N = Cells(Rows.Count, "M").End(xlUp).Row
For i = 1 To N
ch = Left(Cells(i, "M").Value, 1)
If ch = "a" Or ch = "A" Then Kount = Kount + 1
Next i
MsgBox Kount
End Sub
编辑#1:
如果单元格可以包含多个单词(以空格分隔),则使用:
Sub ACount()
Dim i As Long, N As Long, Kount As Long
Dim ch As String
Kount = 0
N = Cells(Rows.Count, "M").End(xlUp).Row
For i = 1 To N
arr = Split(Cells(i, "M").Value, " ")
For Each A In arr
ch = Left(A, 1)
If ch = "a" Or ch = "A" Then Kount = Kount + 1
Next A
Next i
MsgBox Kount
End Sub
推荐阅读
- c# - 带有前缀 id 的 Razor 页面路由
- amazon-web-services - 用于重定向浏览器 http 请求的 AWS 无服务器服务?
- c++ - char[] 的模板特化
- jira - JQL 查询获取所有状态为“待合并”的 jira 票证,并按状态更新的升序对其进行排序
- c# - 使用 USB 令牌签署平面文件
- log4j - 将 log4j.xml 转换为 log4j2.xml 的实用程序
- java - 使用 Java 驱动程序运行 Mongodb 聚合查询时如何获取更新的记录数
- javascript - 带有滚动捕捉的简单 scrollX 元素,更改页码
- reactjs - React-i18next 不会在页面重新加载时加载翻译
- nginx - 使用反向代理 Nginx 在远程服务器中下载文件