Excel VBA仅连接已过滤列的可见单元格。包含测试代码

时间:2014-08-18 15:53:41

标签: excel vba excel-vba concatenation

美好的一天,

我正在尝试将已过滤的列连接到用逗号分隔的单个单元格中。我对编码知之甚少,经过几个小时的搜索后,其他人提供的代码也是如此。

到目前为止,这个功能可以工作,但也可以连接不可见的,过滤掉的单元格:

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

这一个很好用,它也会删除范围内的重复项,但也有同样的问题:

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

是否可以更改这两个函数以忽略列中不可见的,过滤掉的单元格?

感谢阅读,

布赖恩

2 个答案:

答案 0 :(得分:0)

考虑:

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

答案 1 :(得分:0)

当然 - 在你的函数内部和任何可执行指令之前,声明一个新变量myRangeVisible,如下所示:

Dim myRangeVisible as Range

并将其设置为仅包含myRange内部的可见单元格

Set myRangeVisible = myRange.SpecialCells(xlCellTypeVisible)

并将此范围用作功能代码中所有操作的源范围

相关问题