从 Access vba 关闭 Excel 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21800114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Close Excel file from Access vba
提问by Dmitry Pavliv
I have created an excel xls file from Access vba.
我从 Access vba 创建了一个 excel xls 文件。
Private Sub ModifyXl()
Dim XLapp As Excel.Application
Dim xlWB As Excel.Workbook
Set XLapp = New Excel.Application
Dim xlSh As Excel.Worksheet
Set xlWB = XLapp.Workbooks.Open(DskTp & "NHL Doctors.xls", , False)
Set xlSh = xlWB.Sheets("NHLDocs")
Cells.Select
Selection.Font.Name = "Trebuchet MS"
Rows("1:1").Select
Selection.Font.Bold = True
Range("A1").HorizontalAlignment = xlCenter
Columns("A:A").EntireColumn.AutoFit
xlWB.Save
xlWB.Close
XLapp.Quit
Set XLapp = Nothing
End Sub
'Cells.Select' didn't work but the file now exists. I can't delete it because it says it is already open - but it doesn't appear as open.
“Cells.Select”不起作用,但文件现在存在。我无法删除它,因为它说它已经打开 - 但它没有显示为打开。
I have trawled the internet trying to find code that will close the file and quit excel - without success. Help!
我在互联网上搜索,试图找到可以关闭文件并退出 excel 的代码——但没有成功。帮助!
回答by Dmitry Pavliv
Your code didn't work, because you haven't activated sheet (add xlSh.Activate
).But it's not the best way of solving your problem. Try to avoid using Select/Active statementsas in following code:
您的代码不起作用,因为您尚未激活工作表(添加xlSh.Activate
)。但这不是解决问题的最佳方法。尽量避免使用 Select/Active 语句,如下代码所示:
Private Sub ModifyXl()
Dim XLapp As Excel.Application
Dim xlWB As Excel.Workbook
Set XLapp = New Excel.Application
Dim xlSh As Excel.Worksheet
'Dim DskTp as String
'DskTp = "C:\"
Set xlWB = XLapp.Workbooks.Open(DskTp & "NHL Doctors.xls", , False)
Set xlSh = xlWB.Sheets("NHLDocs")
With xlSh
.Cells.Font.Name = "Trebuchet MS"
.Range("1:1").Font.Bold = True
.Range("A1").HorizontalAlignment = xlCenter
.Range("A:A").EntireColumn.AutoFit
End With
xlWB.Close True
Set xlWB = Nothing
XLapp.Quit
Set XLapp = Nothing
End Sub
BTW, can't find where you initialized DskTp
variable (is it a global variable?). I've added it's initialization as comments (in the case you're not using global variable - uncomment thouse lines).
顺便说一句,找不到初始化DskTp
变量的位置(它是全局变量吗?)。我已将它的初始化添加为注释(如果您不使用全局变量 - 取消注释 thouse 行)。