2016-10-04 61 views
0

我正在處理VBA宏,並在一個部分中,我需要它來計算電子表格的數量,但與扭曲。某些工作表將具有相同的名稱並計入表單,工作表(1),工作表(2)。我需要這些表爲 作爲一個組計算,所以表將= 3而不是單獨。VBA Excel計數相同的紙張名稱發生

碼的一個簡單例子,我發現來說明:

Sub aTest() 

Dim myArray() As Variant, dict As Object 
Dim i As Long, v As Variant 
myArray=Array("Apple","Orange","Pineapple", 
"Banana","Banana(1)","Apple","Banana(2)", 
"Pineapple(1)","Pineapple(2)") 
Set dict = CreateObject("Scripting.Dictionary") 

For i = LBound(myArray) To UBound(myArray) 
    If dict.exists(myArray(i)) Then 
     dict.Item(myArray(i)) = dict.Item(myArray(i)) + 1 
    Else 
     dict.Add myArray(i), 1 
    End If 
Next i 

For Each v In dict.keys 
    MsgBox v & " " & dict.Item(v) 
Next v 

End Sub 

蘋果被計數爲2,以及橙色爲1,但香蕉,菠蘿 計數單獨而不是作爲一個組。我需要什麼來讓 計數忽略這些表單末尾的「(#)」?

回答

1

看那排列項目,並檢查是否有「(」如果你找到它,你做檢查本身之前刪除文本的一部分。

這應該做你所需要的。讓我知道如果你需要的任何進一步的信息

Sub aTest() 

Dim myArray() As Variant, dict As Object 
Dim i As Long, v As Variant, bracketPos As Long 

myArray = Array("Apple", "Orange", "Pineapple", "Banana", "Banana(1)", _ 
      "Apple", "Banana(2)", "Pineapple(1)", "Pineapple(2)") 
Set dict = CreateObject("Scripting.Dictionary") 

For i = LBound(myArray) To UBound(myArray) 
    bracketPos = InStr(myArray(i), "(") 
    If bracketPos > 0 Then 
     myArray(i) = Left(myArray(i), bracketPos - 1) 
    End If 

    If dict.Exists(myArray(i)) Then 
     dict.Item(myArray(i)) = dict.Item(myArray(i)) + 1 
    Else 
     dict.Add myArray(i), 1 
    End If 
Next i 

For Each v In dict.keys 
    Debug.Print v & " " & dict.Item(v) 
Next v 

End Sub 

這將產生以下的輸出:!

Apple 2 
Orange 1 
Pineapple 3 
Banana 3 
+1

感謝戴夫「bracketPos」就是我一直在尋找我知道有一些方法來識別它,真不敢沒想到它是非正式的。 –