简体   繁体   中英

vba open file in same folder dynamically

Is it possible to have a number of worksheets in a folder called eg Tom Dick and Harry and a fourth called admin. Admin has a some data input cells one of which has a drop down menu to select Tom Dick or Harry. Then when the macro is triggered it does stuff on the relevant worksheet? I'm learning fast how to do the stuff from all of the other great QA's here, but I can't find anything specific enough. Ive read that this may work:

Workbooks.Open Filename:=ThisWorkbook.Path & "Tom.xls"

But how to make it more dynamic so that it could open Dick or Harry depending on the drop down selection?

Cheers in anticipation :-)

Let me expand on my comment a bit here. First, we will assume you have 4 workbooks in a folder: "Tom, "Dick", "Harry" and "admin". Let's also assume the worksheet in which you input data in the workbook "admin", is likewise called "admin". In the worksheet "admin", you have data validation in cell A1 that allows a user to choose one of three strings: "Tom", "Dick" and "Harry". I would do something like:

Dim admin as Workbook, wb as Workbook
Dim str as String

Set admin = Thisworkbook 'assuming you are writing this code in the workbook admin, which seems to be the case
str = admin.Sheets("admin").Range("A1").Value2
Set wb = Workbooks.Open(admin.Path & "\" & str & ".xls") 'assuming the files are .xls, just change the extension if they are otherwise

Given this, you have a workbook variable wb that allows you to do things to the workbook after it's open.

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