Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing sheets in another workbook by codename using VBA [duplicate]

Tags:

excel

vba

I am attempting to copy data from one workbook to my current workbook using VBA. InputBook is a workbook object referring to the file from which I would like to extract data. The main issue has to do with referencing particular worksheets in the InputBook workbook. In InputBook, I have a worksheet named "Lines" with the codename LINES. I would prefer to reference this worksheet by its codename, for example:

NumItems = WorksheetFunction.CountA(InputBook.LINES.Columns(1))

This clearly doesn't work and I know I can make it function by using either of the following:

NumItems = WorksheetFunction.CountA(InputBook.Sheets("Lines").Columns(1))
NumItems = WorksheetFunction.CountA(InputBook.Sheets(2).Columns(1))

I would, however, rather not use either of those methods as they seem to be less robust. Is there any way to reference the codename of a worksheet object in another open workbook? Thanks.

like image 861
teepee Avatar asked Mar 07 '14 17:03

teepee


People also ask

How do I copy VBA code from one sheet to another?

Open both the workbook that contains the macro you want to copy, and the workbook where you want to copy it. On the Developer tab, click Visual Basic to open the Visual Basic Editor. , or press CTRL+R . In the Project Explorer pane, drag the module containing the macro you want to copy to the destination workbook.

Can an Excel macro pull data from another workbook?

Notes. This macro allows you to get data from another workbook, or put data into it, or do anything with that workbook. The code is a template that allows you to simply access another Excel file.


1 Answers

You can "hack" a reference to another workbook sheet code name by:

Sub UseCodeNameFromOutsideProject()
    Dim WS As Worksheet
    With Workbooks("InputBook .xls")
        Set WS = _
            .Worksheets(CStr(.VBProject.VBComponents("Lines").Properties(7)))
        debug.print WS.Name
    End With
 End Sub

Your WS object is now set to the sheet which has the codename "Lines" in this example.


Original inspiration is here.

like image 142
enderland Avatar answered Oct 20 '22 03:10

enderland