唯一值范围列表

时间:2018-03-31 15:21:10

标签: excel-vba vba excel

我使用以下代码从不同的工作表中提取唯一值并将其粘贴到另一个工作表中。代码运行得非常快,非常棒。但是,我无法弄清楚如何仅将数据粘贴为值而不是复制原始格式。我知道您需要将 .PasteSpecial xlValues 设置为特定范围,但是当我尝试这样做时,我收到错误1004。

任何建议都必须得到赞赏。谢谢!

Option Explicit

Sub Uniquevalues()
Dim lastrow As Long

Dim wk As Worksheet
Dim wk1 As Worksheet


Set wk = Sheets("X")
Set wk1 = Sheets("Y")


lastrow = Cells(Rows.Count, "B").End(xlUp).Row

    wk.Range("B3:B" & lastrow).AdvancedFilter _
    Action:=xlFilterCopy, _
    CopyToRange:=wk1.Range("c4"), _  ' tried to set afer ("c4") .PasteSpecial xlValues, but it doesn't  work
    Unique:=True
    'wk1.Range("c4").PasteSpecial xlValues - tried like this as well and it doesn't work
End Sub

这就是我摆脱复制格式单元格的方法:

Sub format()

Dim wk2 As Worksheet
Dim lastrow1 As Long

Set wk2 = Sheets("Y")

lastrow1 = wk2.Cells(Rows.Count, "C").End(xlUp).Row
wk2.Range("c4:c" & lastrow1).Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
.ClearFormats

End With

End Sub

1 个答案:

答案 0 :(得分:0)

如果没有您的数据,我无法对此进行测试,但请尝试以下操作:

Option Explicit

Sub Uniquevalues()

    Dim wk As Worksheet, wk1 As Worksheet, lastrow As Long
    Set wk = Sheets("X")
    Set wk1 = Sheets("Y")

    lastrow = wk.Cells(Rows.Count, "B").End(xlUp).Row
    wk.Range("B3:B" & lastrow).AdvancedFilter xlFilterCopy, , wk1.Range("c4"), True

End Sub

请参阅:Range.AdvancedFilter Method (Excel)