Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

excel

vba

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() will get me a simple local reference: $A$1. I know it can also be called as Address(External:=True) to get a reference including the workbook name and worksheet name: [Book1]Sheet1!$A$1.

What I want is to get an address including the sheet name, but not the book name. I really don't want to call Address(External:=True) and try to strip out the workbook name myself with string functions. Is there any call I can make on the range to get Sheet1!$A$1?

like image 955
Micah Avatar asked Sep 25 '08 02:09

Micah


People also ask

How do you reference a worksheet and range in VBA?

The basic syntax of the VBA range property consists of the keyword “Range” followed by the parentheses. The relevant range is included within double quotation marks. For example, the following reference refers to cell C1 in the given worksheet and workbook.

How do I find my current workbook name?

Select a blank cell, type =GetBook() into the cell, then press the Enter key. You can see the workbook name is populated on the selected cell.

How do you reference a named range in excel VBA?

To name a selected range, click the name box at the left end of the formula bar, type a name, and then press ENTER.


1 Answers

Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:

Dim cell As Range Dim cellAddress As String Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1) cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False) 

EDIT:

Modify last line to :

cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False)  

if you want it to work even if there are spaces or other funny characters in the sheet name.

like image 85
Ben Hoffstein Avatar answered Oct 03 '22 20:10

Ben Hoffstein