Excel VBA Open workbook, perform actions, save as, close

前端 未结 2 432
南旧
南旧 2020-12-05 21:21

This question has been edited due to lengthy comments and updates from proposed answers.

As requested here is module 13;

Sub SaveInFormat()
Applicati         


        
2条回答
  •  遥遥无期
    2020-12-05 21:45

    After discussion posting updated answer:

    Option Explicit
    Sub test()
    
        Dim wk As String, yr As String
        Dim fname As String, fpath As String
        Dim owb As Workbook
    
        With Application
            .DisplayAlerts = False
            .ScreenUpdating = False
            .EnableEvents = False
        End With
    
        wk = ComboBox1.Value
        yr = ComboBox2.Value
        fname = yr & "W" & wk
        fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"
    
        On Error GoTo ErrorHandler
        Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    
        'Do Some Stuff
    
        With owb
            .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
            .Close
        End With
    
        With Application
            .DisplayAlerts = True
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    
    Exit Sub
    ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
    
    Else: Call Clear
    
    End Sub
    

    Error Handling:

    You could try something like this to catch a specific error:

        On Error Resume Next
        Set owb = Application.Workbooks.Open(fpath & "\" & fname)
        If Err.Number = 1004 Then
        GoTo FileNotFound
        Else
        End If
    
        ...
        Exit Sub
        FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
    
        Else: Call Clear
    

提交回复
热议问题