Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

excel - How to reference an open workbook with a macro that is stored in my "Personal.xlsb" workbook?

I am trying to copy data from any previously made workbook. My macro works as far as selecting the file to copy from and up until the paste line. It fails at ThisWorkBook.Worksheets("Imported Data").Range("A1").PasteSpecial xlPasteValues The "Imported Data" is sheet 4 in the currently open workbook. I believe the problem might be that the macro is running from my "Personal.xlsb" workbook (which is blank) so it cant find the correct sheet to paste to. How would I reference the current open workbook if the name changes each time a new one is made.

Sub Get_Data_From_File()

    Dim FileToOpen As Variant
    Dim OpenBook As Workbook

    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your file 
    & Import Range", FileFilter:="Excel Files(*.xlsx*),*xlsx*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(3).Range("A1:F27").Copy
        ThisWorkBook.Worksheets("Imported 
    Data").Range("A1").PasteSpecial xlPasteValues
        OpenBook.Close False
    
    End If
Application.ScreenUpdating = True

End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just assume it, but do it prior to your call to Application.Workbooks.Open() because that changes the current workbook.

Before you set OpenBook, set a new variable Set TargetRange = Worksheets("Imported Data").Range("A1"). (or you could use ActiveWorkbook.Worksheets...) Then you can change

ThisWorkBook.Worksheets("Imported Data").Range("A1").PasteSpecial xlPasteValues

to

TargetRange.PasteSpecial xlPasteValues

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...