Search code examples
vbaexcelxlsm

Closing a "At statup, open all files in:" file


I currently have a folder set up on my C drive called "XL Startup". This is referenced to open all files in this folder when Excel is started.

The files that exist within this folder is called "mymacros.xlsm" & "CopyMacro.xlsm". These are files that hold macros and hide in the background like so..

Private Sub Workbook_Open()
    Me.Activate
    ActiveWindow.Visible = False
End Sub

mymacros.xlsm will be updated via a macro in CopyMacro.xlsm. This will make sure mymacros.xlsm stays up to date. However, when I call mymacros.xlsm to close, I get an error saying: Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus. How could I go along of getting this to work?

Code within "CopyMacro.xlsm":

Sub Copy_One_File()

If Dir("C:\XL Startup", vbDirectory) = "" Then
MsgBox "Please create a folder named 'XL Startup' at C:\"
Else

    'Close Current Opened Macro
    Workbooks("C:\XL Startup\mymacros.xlsm").Close SaveChanges:=False 'ERROR HERE

    'Copy File
    FileCopy "S:\newversion\mymacros.xlsm", "C:\XL Startup\mymacros.xlsm"

    'Re-open Macro
    Workbooks.Open "C:\XL Startup\mymacros.xlsm"

    MsgBox "msgbox file copied"
End If

End Sub

Solution

  • You are trying to refer to the Workbook via path, but Workbooks() collection only accepts index so you cannot use a path to workbook ->

    Workbooks("C:\XL Startup\mymacros.xlsm").Close SaveChanges:=False
    

    But you can refer to the mymacros.xlsm index ->

    Workbooks("mymacros.xlsm").Close SaveChanges:=False
    

    Check the MSDS for Workbooks() collection reference

    Use Workbooks(index), where index is the workbook name or index number