我想找出用户在Excel工作表中选择的单元格的名称。为清晰起见,请查看下图。在示例中,我需要使用VBA宏检索所有单元名称(A1,B1,C1,D1,E1,F1)。
我能够找出选择了多少个单元格,但不知道如何检索它们的名称。
答案 0 :(得分:3)
如果您希望将名称存储到数组中,则需要遍历该范围内的所有单元格,并将每个单元格的地址存储到数组或集合中。这是一个让您入门的示例:
Public Sub TestIt()
Dim addressArr() As String
Dim i As Long
addressArr = GetSelectedCells(Selection)
For i = LBound(addressArr) To UBound(addressArr)
MsgBox addressArr(i)
Next i
End Sub
Public Function GetSelectedCells(selectedRng As Range) As String()
Dim cellArr() As String
Dim cell As Range
Dim i As Long
ReDim cellArr(0 To (selectedRng.Cells.Count - 1))
i = 0 'setup index for storing to array
For Each cell In selectedRng
cellArr(i) = cell.Address(False, False) 'modify the address here to get reference style
i = i + 1
Next cell
GetSelectedCells = cellArr
End Function