vbaexcelexcel-2003

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


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?


Solution

  • The answer is Yes.

    Try the following code to make changes to external.xls:

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

    I added ActiveWorkbook. to line 4.

    This has to be added to make changes in the currently active workbook (external.xls) and not the workbook containing and executing the macro (internal.xls)