2014-01-30 22 views
1

嗨,我試圖創建一個宏,這將循環通過我的工作表,並找到一個特定的文本字符串。一旦發現字符串我希望它看到它旁邊的列,並且如果它說的是PoweredOn或PoweredOff,然後將1加到計數器上,然後在最後顯示數字。在VBA Excel中計算字符串的問題

在我的Excel中,我有列A作爲我的虛擬機,列B是電源狀態我有一個循環設置來尋找一個虛擬機是一個模板,並打開電源,但是當我運行我的宏時,它作爲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作爲結果嗎?我還需要讓我看看我的系統上的其他模板,同時保留值的數量,我需要爲每個模板創建一個循環,或者我可以使用數組來做到這一點?

+0

那麼A列中的單元格只能包含「vCloud Cell Template」或「」「'? –

+0

是的,我只希望它計算包含完整字符串的單元格。 – LizzardMan

回答

1

試試這個

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和關閉

=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 
+2

您也可以將這兩個公式放在「工作表」上,讓他們不斷更新而不需要任何VBA。 –

+0

工作就像一個魅力非常感謝:) – LizzardMan

+0

@MarkFitzgerald我認爲這是顯而易見的,因爲我實際上列出了'= COUNTIFS(A:A,「vCloud細胞模板」,B:B,「PoweredOn」),但我想它可能對未來的訪問者有所幫助,以便爲您的評論+1) – 2014-01-30 11:21:39