首页 > 解决方案 > 如何修复从 Access 内部关闭 Excel

问题描述

我想使用 VBA 代码从 Access 内部关闭 Excel 工作簿。以下代码打开工作簿并正确运行工作簿中的 VBA 模块。使用我想避免的标准保存对话框关闭工作簿提示。

我尝试将语句修改.Workbooks.Close.Workbooks.Close SaveChanges:=True但实际上使代码崩溃。

Public Function Open_Share_Price_Excel()

' Change Cursor to Hourglass
Screen.MousePointer = 11

Dim Expath, ModName As String
Dim XLApp As Object
Set XLApp = CreateObject("Excel.Application")

'
'Define where the Excel Spreadsheet is and the module to run
'

Expath = "C:\Users\peter\Documents\Financial Affairs\Shares\Share Price Bing.xlsm"
ModName = "Combined_Module"

With XLApp
    .Application.Visible = True
    .Application.DisplayAlerts = False
    .UserControl = True
    .Workbooks.Open Expath
    .Run ModName
    .Workbooks.Close
End With

XLApp.Quit
Set XLApp = Nothing

'Change Cursor back and display finished message

Screen.MousePointer = 0
MsgBox ("Price Update Finished - OK to Continue")

End Function

我尝试将语句修改.Workbooks.Close.Workbooks.Close SaveChanges:=True但实际上使代码崩溃。

欢迎任何建议。

其次,我想确保关闭所有 excel 工作簿,因为我知道工作簿 Personal.xlsx 也可能是打开的。当我手动关闭 Excel 电子表格时,它会关闭,但 EXcel 会立即以空白工作簿重新打开。

请帮助这个新手

标签: excelvbams-access

解决方案


  1. 您需要做的是将打开的工作簿设置为一个变量Set OpenedWb = .Workbooks.Open(Expath),这样您就可以准确地访问该工作簿来关闭它OpenedWb.Close SaveChanges:=True

    .Workbooks.Close不起作用,因为Workbooks代表所有工作簿而不是特定工作簿(但您必须自行关闭每个工作簿)。

  2. 请注意,Dim Expath, ModName As String仅声明ModName As Stringbut Expath As Variant。在 VBA 中,您需要为每个变量指定一个类型,否则Variant默认情况下。所以你必须使用:Dim Expath As String, ModName As String使它们成为两个字符串。

  3. Function不返回任何东西。因此它应该是一个过程Sub而不是一个函数。

你最终会使用类似下面的东西:

Public Sub Open_Share_Price_Excel()    
    ' Change Cursor to Hourglass
    Screen.MousePointer = 11
    
    '
    'Define where the Excel Spreadsheet is and the module to run
    '
    Dim Expath As String 
    Expath = "C:\Users\peter\Documents\Financial Affairs\Shares\Share Price Bing.xlsm"
    Dim ModName As String
    ModName = "Combined_Module"

    Dim XLApp As Object
    Set XLApp = CreateObject("Excel.Application")
    With XLApp
        .Application.Visible = True
        .Application.DisplayAlerts = False
        .UserControl = True
    
        Dim OpenedWb As Object
        Set OpenedWb = .Workbooks.Open(Expath)
    
        .Run ModName
    
        OpenedWb.Close SaveChanges:=True
    End With

    XLApp.Quit
    Set XLApp = Nothing
    
    'Change Cursor back and display finished message
    Screen.MousePointer = 0

    MsgBox ("Price Update Finished - OK to Continue")
End Sub

推荐阅读