简体   繁体   中英

VBA EXCEL: Get values from other (open) workbook (XML) based on partial name and copy these in main workbook

My problem is:

I have 2 workbooks:

Main workbook this is the one where I want the values pasted in.

The other workbook changes its name frequently but always starts with "PR14" and it is a XML file extension (I don't know if thats important or not)

So what the code needs to do is recognize the workbook name "PR14" and then copy the values (let's say for example Cell A1:A3) to the main workbook in cell A1.

The code i got is this:

Sub Recognize()
    For Each wb In Workbooks
        If Left(wb.Name, 4) = "PR14" Then wb.Activate
    Next
End Sub

which seems to work, or at least it recognizes the correct workbook. But how do I go from here?

You're on the right track - As I said in my comments, the easiest way might just be to record a macro that copies across the data you want and place your logic above it to select the correct workbook.

Another way (preferred) would be to set workbook variables so you can have more control over what you're doing.

That would look something like this:

Sub CopyFrom()

Dim wb As Workbook
Dim ThisBook As Workbook
Dim PR14Book As Workbook

    Set ThisBook = ThisWorkbook

    For Each wb In Workbooks
        If Left(wb.Name, 4) = "PR14" Then Set PR14Book = wb
    Next

    ' Whatever kind of stuff you want to do... Just an example:
    ThisBook.Sheets("Sheet1").Range("A1").Value = PR14Book.Sheets("Sheet1").Range("A1:A3").Value
End Sub

Hope that helps set you on the right path and good luck!!

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