VBA加入相当于集合

kar*_*low 3 collections excel vba join excel-vba

如何在VBA中加入集合.在VB.net中,我通常使用Join(...,"delimiter)连接数组,但我无法弄清楚如何使用VBA中的集合来完成此操作.

Dim oColl As New Collection
Dim r As Range

Set r = ThisWorkbook.Sheets("Work1").Range("D13:D263")

For Each cell In r
     If IsEmpty(cell) Then

     Else
         oColl.Add ("a = ''" + cell.Text + "'' ")
     End If
Next
Run Code Online (Sandbox Code Playgroud)

我现在需要将所有集合值连接成一个字符串

bre*_*tdj 5

当您解决了问题后,您可以加快代码速度

  1. 使用SpecialCells非空白而不是测试每个单元格
  2. 使用变量数组而不是范围循环

下面的代码Join用于将最终字符串合并在一起.如果你没有字符串操作("a = ''" + cell.Text + "'' "部分),那么你可以简单地加入第1步中的specialcells范围

更新以处理SpecialCells Collection中的多个区域和单个单元格(varinats不会工作"

Sub Diff()
Dim rng1 As Range
Dim rng2 As Range
Dim varTest
Dim strOut As String
Dim lngrow As Long
On Error Resume Next
With Range("D13:D263")
    Set rng1 = .SpecialCells(xlCellTypeConstants)
    If Not rng1 Is Nothing Then
        Set rng1 = Union(rng1, .SpecialCells(xlCellTypeFormulas))
    Else
        Set rng1 = .SpecialCells(xlCellTypeFormulas)
    End If
End With
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
For Each rng2 In rng1.Areas
    If rng2.Cells.Count > 1 Then
        varTest = Application.Transpose(rng2)
        For lngrow = 1 To UBound(varTest)
            varTest(lngrow) = "a = ''" & varTest(lngrow) & "'' "
        Next
        strOut = strOut & Join(varTest, ",")
    Else
        strOut = strOut & "a = ''" & rng2.Value & "'' "
    End If
Next
MsgBox strOut
End Sub
Run Code Online (Sandbox Code Playgroud)

  • +1.关于`SpecialCells`和`Union`的食物建议 (2认同)