Can a macro in one workbook make changes to another workbook?

Ali picture Ali · Jul 25, 2011 · Viewed 33.8k times · Source

I defined a macro in one worksheet(internal.xls) as

Public Sub sheet2test()
   Workbooks.Open Filename:="external.xls"
   Windows("external.xls").Activate
   Sheets("Sheet3").Activate
   Range("A5").Value = 5

End Sub

Running this code, opens external.xls, and activates its sheet 3. However the Value of 5 is placed in internal.xls and not external.xls. How do i ensure that the changes are made to the other worksheet?

Answer

Patrick Honorez picture Patrick Honorez · Jul 25, 2011

I would rather use:

dim wb as workbook, sh as worksheet
set wb = workbooks.open("thatWorkbook.xls")
'Now you have a proper reference to the newly opened workbook !
set sh = wb.sheets("sheet3")
sh.range("a1") = "hello world"

As stated by others, the various Activate instructions are more inconvenient than useful here.