Excel 阵列重复问题

Excel 阵列重复问题,excel,vba,Excel,Vba,我正在尝试创建一个表,其中包含特定类型的对象和数据集中出现的次数。我尝试创建两组数组来首先索引订单类型,如果订单类型已经存在于第一个数组中,则将1添加到引用数组中。我遇到的问题是,每一行都被索引为它自己的类型,并返回一个1。这是我使用的代码 Sub Comparison() Dim Sheet As Worksheet Dim Book As Workbook Set Book = Excel.ActiveWorkbook Set Sheet = Book.Sheets("Sheet1")  

我正在尝试创建一个表,其中包含特定类型的对象和数据集中出现的次数。我尝试创建两组数组来首先索引订单类型,如果订单类型已经存在于第一个数组中,则将1添加到引用数组中。我遇到的问题是,每一行都被索引为它自己的类型,并返回一个1。这是我使用的代码

Sub Comparison() 
Dim Sheet As Worksheet
Dim Book As Workbook
Set Book = Excel.ActiveWorkbook
Set Sheet = Book.Sheets("Sheet1")
 
Dim i As Integer
Dim c As Integer 'counter for number of items needed in array
Dim arr() As String 'type of order
Dim occ() As Long
For i = 2 To 31
If Sheet.Cells(i, 3).Value <> "" And Sheet.Cells(i, 2).Value <> "" Then
If isThere(Sheet.Cells(i, 2).Value, arr, c) = -1 Then
c = c + 1
ReDim Preserve arr(1 To c)
arr(c) = Sheet.Cells(i, 2).Value
ReDim Preserve occ(1 To c)
occ(c) = 1
Else
occ(isThere(Sheet.Cells(i, 2).Value, arr, c)) = occ(isThere(Sheet.Cells(i, 2).Value, arr, c)) + 1
End If
End If
Next i

您可以使用一个字典,而不是使用两个数组

字典有唯一的键和成对的项值,键将是您的单元格值,项将是事件

dim mydict as object
dim i as long
dim myval as variant

set mydict = CreateObject("Scripting.Dictionary") 'If you want to early bind add the reference to microsoft scripting runtime and set mydict to new dictionary

For i = 2 To 31
    myval = .cells(i, 3).value
    'check to see if the key exists
    if mydict.exists(myval) then
         mydict(myval) = mydict(myval) + 1
    else
         mydict.add myval, 1
    end if
next i

修正了这个问题,因为我在StrComp中输入了一个拼写错误,没有意识到它总是返回-1
dim mydict as object
dim i as long
dim myval as variant

set mydict = CreateObject("Scripting.Dictionary") 'If you want to early bind add the reference to microsoft scripting runtime and set mydict to new dictionary

For i = 2 To 31
    myval = .cells(i, 3).value
    'check to see if the key exists
    if mydict.exists(myval) then
         mydict(myval) = mydict(myval) + 1
    else
         mydict.add myval, 1
    end if
next i