Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Excel: return the parent workbook of a range

Tags:

excel

vba

How do I return the name of the Workbook that contains a given range?

Range.Parent gives the parent sheet.... is the parent workbook possible? Something to the effect of Range.ParentWorkbook

like image 828
brietsparks Avatar asked Oct 01 '15 19:10

brietsparks


People also ask

What does the range in VBA return?

Excel VBA Range Object For example, the range property in VBA is used to refer to specific rows or columns while writing the code. The code “Range(“A1:A5”). Value=2” returns the number 2 in the range A1:A5. In VBA, macros are recorded.

What is .parent VBA?

The Parent property of an object returns the parent object of the object. For example, the parent of a Range object is a Worksheet object. The parent of a Worksheet object is a Workbook object. The parent of a Workbook is the Application object.

How do you reference a range in VBA?

If the Excel VBA Range object you want to refer to is a single cell, the syntax is simply “Range(“Cell”)”. For example, if you want to make reference to a single cell, such as A1, type “Range(“A1″)”.


1 Answers

Coming late to the party, note that this can be also done in one line (tested in Excel 2010):

myRange.Worksheet.Parent.name

Macro Man's GetWorkbookName() function would be simply:

Private Function GetWorkbookName(myRange As Excel.Range) As String
    GetWorkbookName = myRange.Worksheet.Parent.name
End Function

example use is the same:

Sub Foo()
    Dim parentWorkbookName As String

    parentWorkbookName = GetWorkbookName(Range("A1"))
    MsgBox parentWorkbookName
End Sub
like image 109
nkatsar Avatar answered Sep 23 '22 23:09

nkatsar