运行以下代码时,我在“If Not UniqueIDs.AddIfAbsent(ID)”行收到运行时错误 438:经过一番研究,UniqueIDs 集合似乎不支持该方法/属性。我对这一切都有点陌生,所以只是想用谷歌搜索所有这一切的术语。
我采取的一些步骤是将 .AddIfAbsent 替换为“If Not UniqueIDs.Exists(ID) then”,并且不使用“ActiveSheet”,而是使用 Dim ws As Worksheet 语句。
我面临的另一个问题是最后一组代码,特别是“对于 SortedUniqueIDs 中的每个 ID”的“ID”部分,我收到编译错误:对于每个控制变量必须是 Variant 或 Object”
我使用的代码如下:
Sub SumUniqueIdentifiers()
'Declare Variables
Dim ID As String
Dim Sum As Double
Dim LastRow As Long
Dim UniqueIDs As New Collection
Dim SortedUniqueIDs As Collection
Sheets("TH").Activate
'Set the last row of the data and Worksheet
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
'Initialize the sum
Sum = 0
'Loop through the data and sum the values for each unique ID
For i = 3 To LastRow
ID = ActiveSheet.Cells(i, 1).Value
'If the ID is new, add to the collection
If Not UniqueIDs.AddIfAbsent(ID) Then
Sum = 0
End If
'Add the value in the next column to the sum
Sum = Sum + Sheets("Sheet1").Cells(i, 2).Value
'Store the sum in the collection
UniqueIDs(ID) = Sum
Next I
'Loop through the collection and print the sums
For Each ID In SortedUniqueIDs
ActiveSheet.Cells(1, 6).Value = ID
ActiveSheet.Cells(LastRow + 1, 7).Value = SortedUniqueIDs(ID)
LastRow = LastRow + 1
Next ID
End Sub
我采取的一些步骤是将 .AddIfAbsent 替换为“If Not UniqueIDs.Exists(ID) then”,并且不使用“ActiveSheet”,而是使用 Dim ws As Worksheet 语句。
目标是总结一组唯一的标识符,如果我在 A 列中有一系列唯一标识符,每个标识符都有多个条目,我想使用 D 列中的数字来总结每个唯一标识符,并将它们打印在 F 列中,总结通过每个唯一的标识符
Collection
对象不支持AddIfAbsent。请改用 Dictionary
对象。
Sub SumUniqueIdentifiers()
'Declare Variables
Dim ID As String, i
Dim Sum As Double
Dim LastRow As Long, LastR
' Dim UniqueIDs As New Collection
' Dim SortedUniqueIDs As Collection
Dim dataR As Range
Dim UniqueIDs As Object
Set UniqueIDs = CreateObject("scripting.dictionary")
Sheets("TH").Activate
'Set the last row of the data and Worksheet
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
'Initialize the sum
Sum = 0
'Loop through the data and sum the values for each unique ID
For i = 3 To LastRow
ID = ActiveSheet.Cells(i, 1).Value
'If the ID is new, add to the dict
If Not UniqueIDs.exsits(ID) Then
UniqueIDs(ID) = 0
Else
UniqueIDs(ID) = UniqueIDs(ID) + Sheets("Sheet1").Cells(i, 2).Value
End If
Next i
'Loop through the collection and print the sums
LastR = LastRow + 1
For Each ID In UniqueIDs
ActiveSheet.Cells(LastR, 6).Value = ID
ActiveSheet.Cells(LastR + 1, 7).Value = SortedUniqueIDs(ID)
LastR = LastR + 1
Next ID
Set dataR = Range(Cells(LastRow + 1, 6), Cells(LastR - 1, 7))
With ActiveSheet.Sort
.SortFields.Clear
.SortFields.Add Key:=dataR.Columns(1), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange dataR
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
End Sub