VBA粘贴单元格存储在另一个工作表中单元格字典

我试图从一个工作表中search一列单元格,find所有的唯一值,然后将这些值粘贴到另一个工作表中的列。 到目前为止,我的代码创build了一个字典,search所需的列,并select该列中的所有唯一值。

Function UniqueRequest() As Long myReqIDCol = ColSearch("id") 'Creates a dictionary filled with each unique value in the "TaskIDList" column and counts them to determine how many unique keys are in the document Set dic = CreateObject("Scripting.Dictionary") For i = 1 To LastRow tmp = Cells(i, myReqIDCol).Value If Not dic.exists(tmp) Then dic.Add tmp, 1 End If Next i End Function 

我也有一个函数来select我想要粘贴单元格的工作表并设置它,以便将值粘贴到所需列中的每个连续空白单元格中。

 Function ReqSheet(input_column As Integer, input_value As Long) As Long Dim rv As Long rv = 1 Sheets("Request Results").Activate Do While Cells(rv, input_column).Value <> "" rv = rv + 1 Loop Cells(rv, input_column).Value = input_value ReqSheet = input_value End Function 

我的问题是,我不完全确定如何将这两者联系起来。 我想用字典的每个值调用ReqSheet函数,但是我尝试过的所有东西都失败了。 对不起,如果这是一个简单的修复,但我真的不能从互联网上find一个很好的解决scheme,我是相当新的VBA。

使用此代码,并更改列没有任何你想使用。

 Function UniqueRequest() As Long myReqIDCol = ColSearch("id") 'Creates a dictionary filled with each unique value in the "TaskIDList" column and counts them to determine how many unique keys are in the document Set dic = CreateObject("Scripting.Dictionary") For i = 1 To LastRow tmp = Cells(i, myReqIDCol).Value If Not dic.exists(tmp) Then dic.Add tmp, 1 End If Next i For Each value in dic.keys ReqSheet(4,value) 'I have taken column 4,you can change it to any no you want. End Function 

关于字典的好处之一就是你可以把它们的值和关键字放到一个数组中,并且一次写入一个范围而不用循环。

 Sub GetUnique() Dim dc As Scripting.Dictionary Dim rCell As Range Set dc = New Scripting.Dictionary For Each rCell In Selection.Cells If Not dc.Exists(rCell.Value) Then dc.Add rCell.Value, rCell.Value End If Next rCell ThisWorkbook.Worksheets("Request Results").Range("A1").Resize(UBound(dc.Keys), 1).Value = _ Application.Transpose(dc.Keys) End Sub 

沿着这些线应该工作。 您只需将input_columnreplace为适当的variables或方法即可find该列。

 Function UniqueRequest() As Long myReqIDCol = ColSearch("id") 'Creates a dictionary filled with each unique value in the "TaskIDList" column and counts them to determine how many unique keys are in the document Set dic = CreateObject("Scripting.Dictionary") For i = 1 To LastRow tmp = Cells(i, myReqIDCol).Value If Not dic.exists(tmp) Then dic.Add tmp, 1 End If Next i For each _Value in dic ReqSheet(input_column, _Value) Next End Function