PDA

View Full Version : Selecting workbook to run macro



Rajesh Kr Joshi
08-23-2012, 10:14 PM
Hi ,

What is the best method to select a workbook to run macro? I have tried 2 different codes (Below), but both of them sometime gives error: 'Subscription out of Range'. Also this seems an intermittent problem as sometime it works fine.


Workbooks("Mydata").Activate



Windows("Mydata").Activate

Thanks
Rajesh

Admin
08-24-2012, 08:12 AM
Hi

No need to activate. Try to explicitly dim the variables. Try something like


Dim wbkSource As Workbook
Dim wbkTarget As Workbook
Dim wksSource As Worksheet
Dim wksTarget As Worksheet
Dim rngTarget As Range


Set wbkSource = ThisWorkbook
Set wbkTarget = Workbooks("Mydata") 'The 'Mydata' workbook must be open

Set wksSource = wbkSource.Worksheets("Sheet1")
Set wksTarget = wbkTarget.Worksheets("Data")
Set rngTarget = wksTarget.Range("A1")

wksSource.Range("A1:D10").Copy rngTarget

Rajesh Kr Joshi
08-24-2012, 08:21 PM
Thanks Admin. It worked:)