试图初始化未知数量的变量

时间:2016-12-08 19:03:43

标签: vba excel-vba excel

我试图初始化词典,但我不知道我需要3或4或10或其他什么。所以我尝试了以下内容:

dim wb1 as workbook
set wb1 = ThisWorkbook
dim strdict as new scripting.dictionary
  For c = 1 To 65536        'for all rows
    If strdict.Exists(wb1.Sheets(1).Cells(1, 4)) Then 
    'if that string has already been logged ie this is not the first pass of the current string, log it
      strdict(wb1.Sheets(1).Cells(1, 4)) = strdict(wb1.Sheets(1).Cells(1, 4)) + 1
    Else
      strdict.Add wb1.Sheets(1).Cells(1, 4), 1                
      'if that string is not present, add it to the dictionary
      dim left(wb1.Sheets(1).cells(1,4), 3) & "log" as Scripting.dictionary
    End If
  Next c

我不能说我感到惊讶

dim left(wb1.Sheets(1).cells(1,4), 3) & "log" as Scripting.dictionary

没有工作,但有没有办法完成我的想法?或者这是vba根本无法做到的事情?

1 个答案:

答案 0 :(得分:2)

根据您发布的代码,我没有看到您需要多个词典。 好像你只想从Col D获得不同的价值和数量?

根据您的解释

编辑更新

dim wb1 as workbook
dim dictCount as new scripting.dictionary
dim dictSub as new scripting.dictionary
dim k, kSub

set wb1 = ThisWorkbook

For c = 1 To 65536 

    k = wb1.Sheets(1).Cells(c, 4)

    'seen this key before?
    If Not dictCount.Exists(k) Then           
        dictCount.Add k, 0
        dictSub.Add k, New Scripting.Dictionary
    End If  

    dictCount(k) = dictCount(k) + 1 'increment count

    'track sub strings
    kSub = Left(k, 3)
    If dictSub(k).Exists(kSub) Then
        'increment the count
        dictSub(k)(kSub)=dictSub(k)(kSub)+1 
    Else
        dictSub(k).Add kSub, 0
    End If                 


Next c
相关问题