使用VBA添加到不规则的单元格选择中



我正试图通过VBA将不规则单元格添加到选择中。

在下面的代码中,工作表的E列中有一些单元格标记为1。它应该循环通过该列并生成一个选择字符串,然后使用该字符串选择a列中的相应单元格,作为单个选择块。

我的问题是,只有将输出字符串转储到备用单元格,然后手动将其复制到VBA中,输出字符串才能工作。

感谢您的想法!

Sub AddToSelection()
Dim B As Worksheet, SelectString As String, RX As String
Set B = ActiveSheet
For C = 1 To 20
If B.Cells(C, 5) = 1 Then

If RX = "" Then
RX = """" & "A" & B.Cells(C, 5).Row
Else
RX = RX & "," & "A" & B.Cells(C, 5).Row
End If
End If
Next C
RX = RX & """"
Range(RX).Select 'does NOT work

''''BUT
B.Cells(1, 10) = RX ' I dump RX into a cell
SelectString = "A3,A5,A8" ' this copied manually from cell above, so is exactly RX
Range(SelectString).Select 'now it works

End Sub

你的引号是关闭的(不应该在开头和结尾添加""""(,但在这里使用Union要好得多:

For C = 1 To 20
If B.Cells(C, 5) = 1 Then
Dim rng As Range
If rng Is Nothing Then
Set rng = B.Cells(C, "A")  ' or B.Range("A" & C)
Else
Set rng = Union(rng, B.Cells(C, "A"))
End If
End If
Next C
If Not rng Is Nothing Then
rng.Select
End If

最新更新