简体   繁体   English

从 Access vba 关闭 Excel 文件

[英]Close Excel file from Access vba

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. “Cells.Select”不起作用,但文件现在存在。 I can't delete it because it says it is already open - but it doesn't appear as open.我无法删除它,因为它说它已经打开 - 但它没有显示为打开。

I have trawled the internet trying to find code that will close the file and quit excel - without success.我在互联网上搜索,试图找到可以关闭文件并退出 excel 的代码——但没有成功。 Help!帮助!

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.您的代码不起作用,因为您尚未激活工作表(添加xlSh.Activate )。但这不是解决问题的最佳方法。 Try to avoid using Select/Active statements as in following code:尽量避免使用 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?).顺便说一句,找不到初始化DskTp变量的位置(它是全局变量吗?)。 I've added it's initialization as comments (in the case you're not using global variable - uncomment thouse lines).我已将它的初始化添加为注释(如果您不使用全局变量 - 取消注释 thouse 行)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM