Excel VBA“其他”语句错误计数

我创build了一个“If Else If Else”语句来计算string中的string。 它计数的关键字/string,我要计算,但它是错误地计数“其他”/其他项目。 如下面红色部分所示,我应该只有6个string应该被标记为“others”,但是它被计算为8.它总共有18行,但是在总的结果中它被计为20.我是VBA中的newby并需要专家提醒。 谢谢。

在这里输入图像说明

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, "XA") 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 

您应该开始row_number在2而不是1,因为单元格N1包含“简短说明”,你可能不想匹配任何东西?

你也循环直到一个空白的单元格,但空白单元格已经被算作一个“其他”单元格,所以这加上“简介”单元格可能占了2个意想不到的其他单元格计数。 所以可能只是将row_number = 0改为row_number = 1Else:改为ElseIf items <> "" then

由于循环之外, count_of_others从不会在迭代后设置为零。 这也应该发生在其他计数器variables上。

删除您的Else后的冒号,然后重试。 看到这个答案作为参考。