簡體   English   中英

從 Access vba 關閉 Excel 文件

[英]Close Excel 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”不起作用,但文件現在存在。 我無法刪除它,因為它說它已經打開 - 但它沒有顯示為打開。

我在互聯網上搜索,試圖找到可以關閉文件並退出 excel 的代碼——但沒有成功。 幫助!

您的代碼不起作用,因為您尚未激活工作表(添加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

順便說一句,找不到初始化DskTp變量的位置(它是全局變量嗎?)。 我已將它的初始化添加為注釋(如果您不使用全局變量 - 取消注釋 thouse 行)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM