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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With