How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

前端 未结 11 1494
眼角桃花
眼角桃花 2020-12-25 10:34

If I have a Range object--for example, let\'s say it refers to cell A1 on a worksheet called Book1. So I know that calling Address()

11条回答
  •  不知归路
    2020-12-25 11:13

    You may need to write code that handles a range with multiple areas, which this does:

    Public Function GetAddressWithSheetname(Range As Range, Optional blnBuildAddressForNamedRangeValue As Boolean = False) As String
    
        Const Seperator As String = ","
    
        Dim WorksheetName As String
        Dim TheAddress As String
        Dim Areas As Areas
        Dim Area As Range
    
        WorksheetName = "'" & Range.Worksheet.Name & "'"
    
        For Each Area In Range.Areas
    '           ='Sheet 1'!$H$8:$H$15,'Sheet 1'!$C$12:$J$12
            TheAddress = TheAddress & WorksheetName & "!" & Area.Address(External:=False) & Seperator
    
        Next Area
    
        GetAddressWithSheetname = Left(TheAddress, Len(TheAddress) - Len(Seperator))
    
        If blnBuildAddressForNamedRangeValue Then
            GetAddressWithSheetname = "=" & GetAddressWithSheetname
        End If
    
    End Function
    

提交回复
热议问题