excelvbscriptwindows-task-scheduler

How to add a VBScript command that renames an Excel File with the previous workday's date to existing VBScript code


I already have a VBA string that is used by Task Scheduler to open a certain workbook "ORCA Refresh" every day. It refreshes all sheets then closes the document.

I need to add a command to this that renames the workbook with the previous workday's date included. For instance, today is 7/29/2025, so the file would have to be renamed "ORCA Refresh 20250728" and saved in the same location.

Here is the string I am currently using:

'Input Excel File's Full Path
  ExcelFilePath = "C:\Users\greeleym\OneDrive - Legrand France\Desktop\ORCA Refresh.xlsm"

'Input Module/Macro name within the Excel File
  MacroPath = "Module1.OrcaRefresh"

'Create an instance of Excel
  Set ExcelApp = CreateObject("Excel.Application")

'Do you want this Excel instance to be visible?
  ExcelApp.Visible = True  'or "False"

'Prevent any App Launch Alerts (ie Update External Links)
  ExcelApp.DisplayAlerts = False

'Open Excel File
  Set wb = ExcelApp.Workbooks.Open(ExcelFilePath)

'Execute Macro Code
  ExcelApp.Run MacroPath

'Save Excel File (if applicable)
  wb.Save

'Reset Display Alerts Before Closing
  ExcelApp.DisplayAlerts = True

'Close Excel File
  wb.Close

'End instance of Excel
  ExcelApp.Quit

'Leaves an onscreen message!
  MsgBox "Your Automated Task successfully ran at " & TimeValue(Now), vbInformation

Solution

  • Assuming your posted code is actually VBScript, and not VBA, since youy're running it from Task Scheduler:

    '...
    '...
    If Weekday(Date) = 2 Then
        dt = Date-3  'if Monday then use last Friday's date
    Else
        dt = Date-1  'else use yesterday's date
    End if
    
    dtFmt = Year(dt) & ZeroPad(Month(dt), 2) & ZeroPad(Day(dt), 2)
    
    wb.SaveAs Replace(excelFilepath, ".xlsm", " " & dtFmt & ".xlsm")
    
    
    
    Function ZeroPad(n, d)
        ZeroPad = Right(String(d,"0") & n, d)
    End Function