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

Categories

0 votes
3.8k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...