gpt4 book ai didi

Excel.Application Object .Quit 使 EXCEL.EXE 运行

转载 作者:行者123 更新时间:2023-12-04 11:24:26 26 4
gpt4 key购买 nike

我在 Windows 10 上使用 MS Access 2013。
我正在尝试打开磁盘上的 Excel 文件,更改列格式和一些列,保存并退出。
Sub 运行,但在 .Quit 之后命令,“EXCEL.EXE”继续运行,随后对该 Sub 的调用将导致运行时错误。
如果我关闭 Access,“EXCEL.EXE”会在任务管理器上消失,但如果我执行“压缩和修复”数据库则不会。
我有另一个 Sub 在磁盘上打开一个 Excel 文件并将所有列的宽度更改为“自动宽度”,然后关闭,这不会让“EXCEL.EXE”运行。
我在 Dims 和 Sets to Nothing、Workbook Closes 等上尝试了不同的线路顺序。
我在这里和其他网站上搜索过。 VBA 的唯一建议是使用类似 ThisWorkbook.Saved = True 的东西。 .我在 .Quit 之前和之后都试过了没有效果。
除此之外,我只找到 VB.NET 或其他环境的解决方案。

Sub changeXLcolumnFormatting()

Dim XL As Object
Set XL = CreateObject("Excel.Application")
XL.Visible = False
XL.DisplayAlerts = False
XL.Workbooks.Open "C:\Users\640344\Desktop\rawDataTest.XLSX"
Dim sht As Worksheet

With XL
Set sht = ActiveWorkbook.Worksheets(1)

Dim rng As Range
Dim i As Integer, j As Integer

field_names = Split("datasistema|Data de Registo|Data Registo CMVM", "|")
sht.Select
end_of_table = sht.UsedRange.Columns.Count

For j = 0 To UBound(field_names)
For i = 1 To end_of_table
Set rng = sht.Cells(1, i)
If InStr(rng.Text, field_names(j)) > 0 Then
sht.Columns(i).NumberFormat = "yyyy-mm-dd HH:MM:ss"
End If
Next i
Next j
End With

Set rng = Nothing
Set sht = Nothing
XL.ActiveWorkbook.Close (True)

XL.Quit
Set XL = Nothing

End Sub

最佳答案

声明并使用特定的 Workbook 对象 - 就像对 Worksheet 和 Range 所做的那样,如下所示:

    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet
Dim rng As Range
   
    Set xls = New Excel.Application
    Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
    Set wks = wkb.Worksheets(1)
Set rng = wks.Range(<something>)
   
' Do stuff.
    wks.Name = "My New Name"
With rng
' Do more.
End With

    wkb.Close True
   
Set rng = Nothing
    Set wks = Nothing
    Set wkb = Nothing
   
    xls.Quit
   
    Set xls = Nothing

另外,不要使用 Select,这仅用于可见用途。而是定义范围。

Cinetyk 的编辑:

使用@Gustav 的指示,执行我想要的并解决问题的代码是:
Sub changeXLcolumnFormatting()

Dim XL As Excel.Application
Dim sht As Excel.Worksheet
Dim wkb As Excel.Workbook
Dim rng As Range

Set XL = New Excel.Application
XL.Visible = False
XL.DisplayAlerts = False

Set wkb = XL.Workbooks.Open("C:\Users\640344\Desktop\rawDataTest.XLSX")
Set sht = wkb.Worksheets(1)

Dim i As Integer, j As Integer

field_names = Split("datasistema|Data de Registo|Data Registo CMVM", "|")
end_of_table = sht.UsedRange.Columns.Count

For j = 0 To UBound(field_names)
For i = 1 To end_of_table
Set rng = sht.Cells(1, i)
If InStr(rng.Text, field_names(j)) > 0 Then
sht.Columns(i).NumberFormat = "yyyy-mm-dd HH:MM:ss"
End If
Next i
Next j

wkb.Close (True)
Set rng = Nothing
Set sht = Nothing

XL.Quit
Set XL = Nothing

End Sub

关于Excel.Application Object .Quit 使 EXCEL.EXE 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42113082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com