简体   繁体   中英

How can I refer to another workbook by the content of a cell in the current workbook?

I'm making a macro in excel 2010 and my goal is that everyone can use this macro for their own work. Therefore I have to make it very flexible.

Everyone names their own workbook (I've solved this in the macro by using ThisWorkbook), but everyone also names their own extraction file (from where the new data comes).

However, almost no-one knows how to work with VBA so it's not possible to adjust this reference in the code every time.

Therefore, I've added a new sheet: 'Personalize'

In here, the person can add the name of the extraction file in a specific cell.

Unfortunately I don't know how to open a workbook that has the name of a specific cell in the current workbook.

I tried, for example, Windows("ThisWorkbook.Sheets("Personalize").Range("B3")").Activate but it didn't work.

The same thing with sheets that can be named differently, I don't know how to adjust them in the macro without using VBA in every case.

Does anyone have any ideas or suggestions?

Thank you so much in advance!

Kind Regards,

Hendrik

If you want to open a workbook that's closed you need the full path:

dim wkb as workbook
dim wbPath as String

wbPath  = ThisWorkbook.Sheets("Personalize").Range("B3").value
Set wkb = Workbooks.Open(wbPath )

If you want to activate a workbook that's already opened, you don't need the full path but the workbook's name (such as "Workbook1.xlsx"). For this you can shave off the path before reaching "Workbook1.xlsx" (alternatively if the workbook is always going to be opened first, just have them enter the workbook's name directly and skip taking out the rest of the path):

dim wbname as String

wbname = ThisWorkbook.Sheets("Personalize").Range("B3").value
Do until Instr(wbname, "\") = 0
     wbname = Mid(wbname, instr(wbname, "\") + 1) 'I didn't test this, just going off the top of my head
Loop

Workbooks(wbName).Activate

Be sure to handle your errors properly. For reference: VBA Excel simple Error Handling

Test what happens when you try to input a name that's incorrect, for example. You want to handle those errors with appropriate messageboxes or the users may feel like your program doesn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM