VBA Excel计数相同的工作表名称出现

时间:2016-10-04 13:52:29

标签: arrays vba excel-vba excel

我正在研究一个VBA宏,在一个部分我需要它来计算电子表格的数量,但有一个扭曲。某些工作表将具有相同的名称,并计为工作表,工作表(1),工作表(2)。我需要这些床单 计为一组,因此纸张将= 3而不是单独。

我发现的代码的一个简单示例:

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 个答案:

答案 0 :(得分: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