简体   繁体   中英

Using Personal.xlsb - referencing active workbook in VBA

I have a number of scripts that are in a module in my Personal.xlsb file. It's kept hidden, but in this script, the idea is that you run it from within a different workbook each time. It opens a separate workbook (source.xlsx), copies a range from it, pastes into the original workbook, and then closes source.xlsx.

When it comes to the "ThisWorkbook.ActiveSheet.Paste" part, it's pasting it into the Personal.xlsb workbook instead of the target workbook that is actually open and visible. How can I make sure it's being pasted in the right workbook? The workbook's filename will always be different, so I can't specify a path or anything like that.

Sub CopyData()
    Application.DisplayAlerts = False
    Dim wbSource As Workbook
    Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
    wbSource.Sheets(1).Range("A1:X105").Copy

    ThisWorkbook.ActiveSheet.Paste
    wbSource.Close
    Application.DisplayAlerts = True
        Call CopyCFormat
End Sub

Don't use ThisWorkbook in most cases, as it references the workbook that the macro is stored in (in this case, personal.xlsb).

Instead, you can use ActiveWorkbook to refer to whichever workbook has focus at the time the macro is run. You can also assign ActiveWorkbook to a variable for easier reference.

Sub CopyData()
Application.DisplayAlerts = False
Dim wbSource As Workbook
Dim wbTarget as Workbook

Set wbTarget = ActiveWorkbook

Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy

wbTarget.ActiveSheet.Paste
wbSource.Close
Application.DisplayAlerts = True
    Call CopyCFormat
End Sub

You could also reference the active sheet without specifying which workbook it's in, as:

Dim wbSource As Workbook
Dim shtTarget as Worksheet

Set shtTarget = ActiveSheet

Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy

shtTarget.ActiveSheet.Paste

Luck!

If I understand it, you should just add another workbook variable.

Sub CopyData()
Dim mainWB  As Workbook
Dim mainWS  As Worksheet
Set mainWB = ActiveWorkbook
Set mainWS = mainWB.Sheets(1)    ' Change this to whatever you need it to be

Application.DisplayAlerts = False
Dim wbSource As Workbook
Set wbSource = Workbooks.Open(Filename:="source.xlsx", UpdateLinks:=3)
wbSource.Sheets(1).Range("A1:X105").Copy

mainWS.Paste
wbSource.Close
Application.DisplayAlerts = True
Call CopyCFormat
End Sub

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