在VBA Excel中计算string的问题

嗨,我想创build一个macros,将循环通过我的工作表,并find一个特定的文本string。 一旦如果发现string,我希望它看到旁边的列,如果它说,PoweredOn或PoweredOff然后加1到计数器,然后显示在最后的数字。

在我的Excel中我有列A作为我的虚拟机和列B是电源状态我有一个循环设置来寻找一个虚拟机是一个模板,并打开电源,但是当我运行我的macros它打印为0在这里是我目前的代码。

Dim POT As Integer Dim POFFT As Integer Sheets("tabvInfo").Select Range("A2").Select Do If ActiveCell.Value = ("vCloud Cell Template") Then If ActiveCell.Offset(0, 1).Value = ("PoweredOn") Then POT = Selection.Cell.Count Else If ActiveCell.Offset(0, 1).Value = ("PoweredOff") Then POFFT = Selection.Cell.Count End If End If End If ActiveCell.Offset(1, 0).Select Loop Until IsEmpty(ActiveCell.Offset(1, 0)) MsgBox ("The number of powerered on VMs is " & POT) MsgBox ("The number of powerered off VMs is " & POFFT) 

谁能告诉我为什么我得到0作为结果? 我还需要使这看看我的系统上的其他模板,同时保留值的计数,我需要为每个模板创build一个循环,或者我可以使用数组来做到这一点?

试试这个

 Sub Main() Dim POT As Long Dim POFFT As Long Dim c As Range For Each c In Sheets("tabvInfo").Range("A2:A" & Sheets("tabvInfo").Range("A" & Rows.Count).End(xlUp).Row) If StrComp(c, "vCloud Cell Template", vbTextCompare) = 0 Then If StrComp(c.Offset(0, 1), "PoweredOn", vbTextCompare) = 0 Then POT = POT + 1 ElseIf StrComp(c.Offset(0, 1), "PoweredOff", vbTextCompare) = 0 Then POFFT = POFFT + 1 End If End If Next MsgBox ("The number of powerered on VMs is " & POT) MsgBox ("The number of powerered off VMs is " & POFFT) End Sub 

它消除了.Select语句和.ActiveCell 。 这是一个简单的循环,实现你想要的。


我不知道你意识到,但你可以使用2个非常简单的公式为PoweredOn和closures

 =COUNTIFS(A:A,"vCloud Cell Template",B:B, "PoweredOn") =COUNTIFS(A:A,"vCloud Cell Template",B:B, "PoweredOFF") 

因此,为了消除使用循环的需要,你可以

 Sub NoLoop() MsgBox "Powered ON: " & Evaluate("=COUNTIFS(A:A,""vCloud Cell Template"",B:B, ""PoweredOn"")") MsgBox "Powered OFF: " & Evaluate("=COUNTIFS(A:A,""vCloud Cell Template"",B:B, ""PoweredOff"")") End Sub