excel - 如何修复从 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 会立即以空白工作簿重新打开。
请帮助这个新手
解决方案
您需要做的是将打开的工作簿设置为一个变量
Set OpenedWb = .Workbooks.Open(Expath)
,这样您就可以准确地访问该工作簿来关闭它OpenedWb.Close SaveChanges:=True
。.Workbooks.Close
不起作用,因为Workbooks
代表所有工作簿而不是特定工作簿(但您必须自行关闭每个工作簿)。请注意,
Dim Expath, ModName As String
仅声明ModName As String
butExpath As Variant
。在 VBA 中,您需要为每个变量指定一个类型,否则Variant
默认情况下。所以你必须使用:Dim Expath As String, ModName As String
使它们成为两个字符串。你
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
推荐阅读
- dask - 如何在 DASK 中批量调度 dask_jobqueue 作业而不是并发?
- python - Kivy Video 类 rtsp 流在其他电脑上不起作用
- java - 无法获取 org.hibernate.persister.entity.SingleTableEntityPersister 的构造函数。空指针异常
- xml - MarkLogic:cts:突出显示特定元素
- c# - 如何使“CacheListenerAdapter”在 ASP.NET 中工作?
- regex - 使用Python根据找词提取三句话
- java - Java中列表的二分查找
- javascript - 如何在 Spring MVC 的客户端处理 JWT 令牌?
- rust - 通过特征对类型的许多可选和独立功能进行抽象的最惯用/最好的方法是什么?
- laravel - 使用 Laravel 选择恰好一个月内最近的记录