如何通过VBA同时选择两个单元格,用不同的代码选择每个单元格,即逐步选择

时间:2016-12-17 13:22:51

标签: excel vba excel-vba

如何逐步在VBA中同时选择单元格,即我不想一次性选择所有单元格,例如一行代码。使用同时选择的Range或Union。我想同时选择单元格(1,2)和单元格(5,4),但一次选择一个。

2 个答案:

答案 0 :(得分:1)

我在excel文件上使用了一个宏,通过选择一个单元格,然后按住控制按钮,然后选择第二个单元格,同时选择两个单元格来查看vba输出是什么。

VBA代码使用范围。我知道你不想使用它。话虽如此,你可以逐渐增加细胞到范围,它将一次一个地选择细胞的外观:

Dim cell1 As String
Dim cell2 As String
Dim cell3 As String

cell1 = "B1"
cell2 = "D5"
cell3 = "B7"

Dim rangeStr As String
rangeStr = cell1
Range(rangeStr).Select ' here it only selects cell B1
rangeStr = cell1 & "," & cell2
Range(rangeStr).Select ' here it incremently also selects cell D5
rangeStr = cell1 & "," & cell2 & "," & cell3
Range(rangeStr).Select ' and here it incremently also selects B7

答案 1 :(得分:0)

你可能想要使用数组

此处是地址方法

Sub Selections()
    Dim rngAddress As String
    Dim myCellsAddresses As Variant, cellAddress As Variant

    myCellsAddresses = Array("B1", "D5", "B7") '<--| collect your cells adresses in an array
    rngAddress = myCellsAddresses(LBound(myCellsAddresses)) '<--| set your first range address as the first cell one
    For Each cellAddress In myCellsAddresses '<--| loop through cells addresses array
        rngAddress = rngAddress & "," & cellAddress '<--| update range address by adding current cell one
        Range(rngAddress).Select '<--| select the resulting range
    Next cellAddress
End Sub

Range 等效方法是:

Sub selections3()
    Dim rng As Range
    Dim myCellsAddresses As Variant, cellAddress As Variant

    myCellsAddresses = Array("B1", "D5", "B7")
    Set rng = Range(myCellsAddresses(0))
    For Each cellAddress In myCellsAddresses
        Set rng = Union(rng, Range(cellAddress))
        rng.Select
    Next cellAddress
End Sub