我创建了一个“If ElseIf Else”语句,用于计算字符串中的字符串。它会计算我想要计算的关键字/字符串,但它会错误地计算“其他”/其他项目。如下图所示以红色突出显示,我应该只有6个字符串应该标记为“其他”,但它计为8.它总共有18行,但在总结果中它将其计为20。 我是VBA的新手,需要专家建议。谢谢。
Option Compare Text
Public Sub Keywords()
Dim row_number As Long
Dim count_of_corp_or_windows As Long
Dim count_of_mcafee As Long
Dim count_of_token As Long
Dim count_of_host_or_ipass As Long
Dim count_of_others As Long
Dim count_of_X As Long
Dim count_of_all As Long
Dim items As Variant
row_number = 0
count_of_corp_or_windows = 0
count_of_mcafee = 0
count_of_token = 0
count_of_host_or_ipass = 0
count_of_X = 0
count_of_others = 0
count_of_all = 0
Do
row_number = row_number + 1
items = Sheets("LoginPassword").Range("N" & row_number)
If InStr(items, "corp") Or InStr(items, "windows") Then
count_of_corp_or_windows = count_of_corp_or_windows + 1
ElseIf InStr(items, "mcafee") Then
count_of_mcafee = count_of_mcafee + 1
ElseIf InStr(items, "token") Then
count_of_token = count_of_token + 1
ElseIf InStr(items, "host") Or InStr(items, "ipass") Then
count_of_host_or_ipass = count_of_host_or_ipass + 1
ElseIf InStr(items, "X A") Then
count_of_X = count_of_X + 1
Else:
count_of_others = count_of_others + 1
End If
Loop Until items = ""
count_of_all = count_of_corp_or_windows + count_of_mcafee + count_of_token + count_of_host_or_ipass + count_of_X + count_of_others
Range("N2").Select
Selection.End(xlDown).Select
lastCell = ActiveCell.Address
ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_corp_or_windows
ActiveCell.Offset(5, 0).Value = count_of_mcafee
ActiveCell.Offset(6, 0).Value = count_of_token
ActiveCell.Offset(7, 0).Value = count_of_host_or_ipass
ActiveCell.Offset(8, 0).Value = count_of_X
ActiveCell.Offset(9, 0).Value = count_of_others
ActiveCell.Offset(11, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Keywords"
ActiveCell.Offset(4, 1).Value = "Corp or Windows"
ActiveCell.Offset(5, 1).Value = "Mcafee"
ActiveCell.Offset(6, 1).Value = "Token"
ActiveCell.Offset(7, 1).Value = "Host or ipass"
ActiveCell.Offset(8, 1).Value = "X accounts"
ActiveCell.Offset(9, 1).Value = "Others"
ActiveCell.Offset(11, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_corp_or_windows / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_mcafee / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_token / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_host_or_ipass / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_X / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_others / count_of_all
End Sub
答案 0 :(得分:2)
您应该将row_number设置为2而不是1,因为单元格N1包含“简短描述”,您可能不希望与任何内容匹配?
此外,您正在循环直到空白单元格,但空白单元格已被计为“其他”单元格,因此这加上“简短描述”单元格可能会占据计数的2个意外其他单元格。所以可能只需将row_number = 0
更改为row_number = 1
,将Else:
更改为ElseIf items <> "" then
答案 1 :(得分:0)
count_of_others
永远不会设置为零,因为它不在循环中。这也适用于其他计数器变量。
答案 2 :(得分:0)
从Else
后删除冒号,然后重试。
请参阅this答案以供参考。