繁体   English   中英

VBA从第x行开始的一列中列出唯一值?

[英]Vba list unique values down a column from row x onwards?

我有两个工作表。

工作表2:

Column C 
A
A
B
B
C
D
E
E
F
G

工作表1:

Column G
A
B
C
D
E
F
G

如上所述,我正在尝试从工作表2的C列中创建工作表1列G的唯一值列表。

到目前为止,这是我的代码:

Sub LIST()
   Dim Col As New Collection
    Dim itm
    Dim i As Long
    Dim CellVal As Variant
    Dim LastRow As Long

    '~~> Lets say looping through Row 1 to 22 For
    '~~> Range("A1:A22") as mentioned in your recent comment

    LastRow = ThisWorkbook.Worksheets("Data").Range("C" & Rows.Count).End(xlUp).Row  'Finds the last used row

    For i = 1 To LastRow
        CellVal = Sheets("Data").Range("C" & i).value
        On Error Resume Next
    Next i

    For Each itm In Columns(7)
    itm
    Next
    End Sub

我是vba的新手,请somsone告诉我如何使它正常工作吗?

PS我需要它来列出从第16行开始的工作表1的G列中的值。

根据达伦的评论:

Sub LIST()
    Dim r1 As Range, r2 As Range

    Set r1 = Sheets("Sheet1").Range("C:C")
    Set r2 = Sheets("Sheet2").Range("G1")

    r1.Copy r2

    r2.RemoveDuplicates Columns:=1, Header:=xlNo
End Sub

如果您希望从第一行开始,则将"C:C"替换为"C7:C" & Rows.Count

用字典的另一种方式

Sub LIST()
    Dim dict As Dictionary
    Dim cell As Range

    Set dict = New Dictionary 
    With Worksheets("Data")
        For Each cell In .Range("C1", .Cells(.Rows.Count, 1).End(xlUp)
            dict.Item(cell.Value) = 1
        Next
    End With 
    Worksheets("Sheet1").Range("G16").Value = Application,Transpose(dict.Keys)
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM