简体   繁体   中英

VBA - retrieve the name of an opened workbook

Here's my problem :

I have a sub in my main file (let's call it mainFile)doing this :

-Opening a file (the user chooses which file to open)

-Retrieve the name of this file in a variable

-Copy value of a few cells in file1, paste them in mainFile

in order to do that, my code looks something like this :

Workbooks.Open file1
fileName = ThisWorkbook.Name
Set source = Workbooks(fileName).Sheets("Feuil1")
Set target = Workbooks(mainFile).Sheets("Feuil1")
source.Range("A5:A66").Copy target.Range("T5")

but the variable fileName, instead of returning, for instance, "file1.xls", returns "mainFile.xls".

I guess it's because the sub is located in mainFile. But what can I use instead of ThisWorkbook.name ?

Thanks

You seem to be doing extra work here that you don't need. We can set a Workbook variable, and use it directly, instead of accessing it by name.

Dim wkbk as Workbook

Set wkbk = Workbooks.Open(file1)
Set source = wkbk.Sheets("Feuil1")
Set target = ThisWorkbook.Sheets("Feuil1")
source.Range("A5:A66").Copy target.Range("T5")

The other option that you have (which is not a good choice, because it can lead to strange and hard to debug errors) is to use ActiveWorkbook , which references the displayed workbbok. In this case, that would be the workbbok you just opened.

That's one of the issues when using This...

Try this code, instead:

Dim NewWB as workbook

Set NewWB = Workbooks.Open file1
fileName = NewWB.Name
Set source = Workbooks(fileName).Sheets("Feuil1")
Set target = Workbooks(mainFile).Sheets("Feuil1")
source.Range("A5:A66").Copy target.Range("T5")

Read How to avoid using Select in Excel VBA macros for tips on avoiding the This... , Active... and Select... statements to eliminate these (and other) types of issues.

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