如何通过VBAselect两个单元格同时select不同的代码,即逐步select每个单元格

如何在VBA中同时select单元格,即我不想一次select所有的单元格,例如使用同时select的Range或Union。 我想同时select单元格(1,2)和单元格(5,4),但每次只select一个。

我在一个excel文件中使用了一个macros,通过select一个单元,然后按住控制button,然后select第二个单元,同时select两个单元,以查看vba的输出结果。

VBA代码使用一个范围。 我知道你不想使用。 这就是说,你可以增加细胞的范围,它将有一个一个select一个单元格的外观如此:

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 

你可能想要使用数组

这是一个地址方法

 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