vba - Excel VBA 打开工作簿、执行操作、另存为、关闭

标签 vba excel automation userform

由于冗长的评论和建议答案的更新,此问题已被编辑。

此处要求的是模块 13;

Sub SaveInFormat()
Application.DisplayAlerts = False
Workbooks.Application.ActiveWorkbook.SaveAs Filename:="C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data\" & Format(Date, "yyyymm") & "DB" & ".xlsx",   leFormat:=51
Application.DisplayAlerts = True
End Sub

错误处理也存在问题,我知道我出错了,但我更感兴趣的是在进入之前修复关闭函数。这是需要一些工作的错误处理代码

Sub test()

Dim wk As String, yr As String, fname As String, fpath As String
Dim owb As Workbook

wk = ComboBox1.Value
yr = ComboBox2.Value
fname = yr & "W" & wk
fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"
owb = Application.Workbooks.Open(fpath & "\" & fname)
On Error GoTo ErrorHandler:
ErrorHandler:
If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then Exit Sub Else Call Clear

'Do Some Stuff

Call Module13.SaveInFormat

owb.Close

这是您的测试代码加上我对文件路径和名称的更改

最佳答案

讨论后发布更新的答案:

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

错误处理:

您可以尝试这样的方法来捕获特定错误:

    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

关于vba - Excel VBA 打开工作簿、执行操作、另存为、关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12951946/

相关文章:

vba - Ms Access - VBA - 以编程方式创建具有大小的标签

windows - 有没有办法将文件夹名称链接到特定单元格?

excel - 如何在Excel中将数字格式化为文本存储?

bash - 使用 expect 来自动执行管道命令

google-cloud-platform - 无法通过 Terraform 使用 GCP Cloud Build 验证 GitHub 存储库

vba - 从文件夹路径获取 Outlook 中的 MAPI 文件夹

vba - 仅保存工作表的表对象值的副本

perl - 从 perl 使用 Inkscape shell

excel - 有没有办法编辑表单控件按钮上的标题?

VBA如何在子程序之间使用变量?