简体   繁体   中英

Excel VBA Concatenate only visible cells of filtered column. Test code included

Good day all,

I'm trying to concatenate a filtered column into a single cell separated with commas. I know little about coding, the code provided are by others after hours of searching.

So far, this function works but also concatenates invisible, filtered out cells:

Function test1(myRange As Range)
Dim aOutput
For Each entry In myRange
    If Not IsEmpty(entry.Value) Then
        aOutput = aOutput & entry.Value & ", "
    End If
Next
test1 = Left(aOutput, Len(aOutput) - 1)
End Function

And this one works well where it will also remove duplicates from the range, but has the same problem:

Function test2(ByRef rRng As Range, Optional ByVal sDelim As String = ", ") As String
Dim oDict As Object
Dim rCell As Range
Dim sTxt As String
Set oDict = CreateObject("Scripting.Dictionary")
With oDict
    For Each rCell In rRng
        If .Exists(rCell.Text) Then
            'Do nothing
        Else
            .Add rCell.Text, rCell.Text
            sTxt = sTxt & sDelim & rCell.Text
        End If
    Next rCell
End With
    test2 = Mid(sTxt, Len(sDelim) + 1)
End Function

Is it possible to alter the two functions to ignore invisible, filtered out cells in a column?

Thanks for reading,

Brian

Consider:

Public Function test1(myRange As Range)
    Dim aOutput As String, entry As Range
    For Each entry In myRange
        If entry.EntireRow.Hidden = False Then
            aOutput = aOutput & entry.Value & ", "
        End If
    Next
    test1 = Left(aOutput, Len(aOutput) - 1)
End Function

Sure - inside your functions and before any executable instruction, declare a new variable myRangeVisible like this:

Dim myRangeVisible as Range

and set it up to include only visible cells from inside myRange

Set myRangeVisible = myRange.SpecialCells(xlCellTypeVisible)

And use this range as your source range for all operations in your functions code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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