仅将可见单元格从 Table 列复制到 Excel VBA 中用逗号分隔的一列,循环

Copy only visible cells from a Table column to one column separated by a comma in Excel VBA, Loop

大家好,所有聪明人,

我正在开发一个宏,它允许我将已筛选列 table 的值复制到以逗号分隔的单个单元格中。我让我的代码适用于未过滤的 table 但我不知道如何让它适用于过滤的列。

之后我想复制单元格的值。

我知道我可能应该使用 SpecialCells(xlCellTypeVisible),但我不知道我的代码在哪里。

此代码从第 11 行开始

Sub Onecell()
Dim i As Integer
Dim count As Integer
Dim s As String
count = Cells(Rows.count, "A").End(xlUp).Row
For i = 11 To count
s = s & Cells(i, 1) & ","
Next
Range("D11") = s

Range("D11").Select
Selection.Copy

End Sub

预期结果如下:

假设我有一个这样的table。

USA     2019
SWEDEN      2019
NORWAY      2019
INDIA       2020
GERMANY     2020
SPAIN       2020

例如,如果我过滤 2019 年的 table,

那么我只想要单元格 D11 美国、瑞典、挪威

如果我过滤 2020 年,那么我想在单元格 D11 印度、德国、西班牙

我很确定问题是我必须把

SpecialCells(xlCellTypeVisible) 某处

非常感谢任何帮助

这应该适合你:

Option Explicit
Sub Onecell()

    Dim count As Integer
    Dim JoinCells As New Scripting.Dictionary 'You need to go to tools-->references--> Check: Microsoft Scripting Runtime
    Dim C As Range

    With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your sheet name
        count = .Cells(.Rows.count, "A").End(xlUp).Row
        For Each C In .Range("A11", .Cells(count, 1)).SpecialCells(xlCellTypeVisible) 'like this you will only loop through visible ones
            If Not JoinCells.Exists(C.Value) Then JoinCells.Add C.Value, 1 'store all the visible items
        Next C
        .Range("D11") = Join(JoinCells.Keys, ", ")
    End With

End Sub