数组类型不匹配

Array type mismatch

我在 Excel sheet 上有来自 Spotify 的收听历史记录。我想从该列表中提取所有独特的艺术家并将它们写在同一 Excel sheet.

的不同列中
Sub CountUniqueValues()

    Dim wb As Workbook
    Set wb = Workbooks("Spotify_Analysis_XYZ.xlsm")
    
    Dim ws As Worksheet
    Set ws1 = wb.Worksheets("Sheet1")
    
    Dim LastRow As Long
    
    LastRow = Cells(Rows.Count, "B").End(xlUp).Row
    
    Dim UniqueArtists As Variant
    UniqueArtists = Evaluate("Unique(" & "B2:B" & LastRow & ",TRUE,FALSE)")
    ws1.Cells("2:40000", 8) = UniqueArtists
    
End Sub

所有艺术家都存储在 B 列中。

我发现类型不匹配。

如果您确保正确工作簿的正确工作表是 Active:

,这将起作用
Sub uniqB2H()
    Dim LastRow As Long
    LastRow = Cells(Rows.Count, "B").End(xlUp).Row
    
    Range("H2").Formula2 = "=Unique(B2:B" & LastRow & ")"
    Range("H2#").Value = Range("H2#").Value
End Sub

编辑#1:

  1. 这种方法避免了必须构建 VBA 数组并将其传输到工作表
  2. 在此演示中,我们假设只有一个工作簿和一个包含数据的工作表已经 Active;因此 none 个范围需要限定
  3. 在此演示中Formula2用于在单元格中放置动态溢出公式
  4. 在此演示中,我们使用 Range("H2#") 指定完整溢出范围。

这是另一种让它起作用的方法。你的最后一行不是一个范围。

Sub CountUniqueValues()

Dim t As Long

Dim wb As Workbook
Set wb = Workbooks("Spotify_Analysis_XYZ.xlsm")

Dim ws1 As Worksheet
Set ws1 = wb.Worksheets("Sheet1")

Dim LastRow As Long

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

Dim UniqueArtists As Variant
UniqueArtists = Evaluate("Unique(Sheet1!B2:B" & LastRow & ",false,FALSE)")
t = UBound(UniqueArtists) - 1
ws1.Range(ws1.Cells(2, 8), ws1.Cells(2 + t, 8)) = UniqueArtists


End Sub