我有一个代码在一个地方运行良好,但在另一个地方则不然。通常,它是一个宏,当您单击按钮时执行,然后执行各种其他操作:它打开另一个文件,执行一些 PowerQuery 操作,然后再次关闭它。
当我尝试将此代码作为 Sub Workbook_Open 放入 ThisWorkBook 中时,它会给我运行时错误。我尝试单独调用这段代码,它一直有效;只是在打开时执行时不会。我尝试在执行之前放置一个计时器,让它“稳定下来”。
这可能是什么原因造成的?
失败的行似乎是这一行:
*ActiveWorkbook.Queries.Add Name:="Liste_All_Masques", Formula:= _*
Public type_reception As String
Public Backup As String
Public Layer_critique As String
Public Masks_backup As String
Public Nom_layer_critique As String
Public Compteur As Integer
Public Statut_mask As String
Public Maskset As String
Public State_Name As String
Public Cinq_digit As String
Public Deux_digit As String
Private Sub Workbook_Open()
Application.ScreenUpdating = False
'On efface l'ancien résultat de repell form
Sheets("Ancien repell form").Activate
Sheets("Repell form").Visible = True
Call Nettoyage_repell_form
Sheets("Repell form").Activate
Range("C2:C30").Clear
type_reception = ""
Backup = ""
Layer_critique = ""
Nom_layer_critique = ""
Compteur = 0
Statut_mask = ""
Maskset = ""
State_Name = ""
'Don't show confirmation window
'Application.DisplayAlerts = False
aFile = "W:\Ateliers\PHOTO\Masks\Reports_TGV_IRETICLE\Liste_All_Masques.xlsx"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
'Ouverture du fichier CSV
Workbooks.Open ("W:\Ateliers\PHOTO\Masks\Reports_TGV_IRETICLE\Liste_All_Masques.CSV")
Set All_masque = ActiveWorkbook
'Workbooks(“Liste_All_Masques.CSV”).Activate
ActiveWorkbook.Queries.Add Name:="Liste_All_Masques", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(""W:\Ateliers\PHOTO\Masks\TPP_Mask\Florent\07 - Macro Renvoi-réception\Tests CSV\Liste_All_Masques.CSV""),[Delimiter=""#(tab)"", Columns=18, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Promoted Headers"" = Table.PromoteHeaders(Source, [PromoteAllScalars=true])," & Chr(13) & "" & Chr(10) & " #""Changed Type"" = Table.TransformColumnTypes(#""Pr" & _
"omoted Headers"",
REDACTED DATA
" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Reordered Columns"""
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:="OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Liste_All_Masques;Extended Properties=""""", Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Liste_All_Masques]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Liste_All_Masques"
.Refresh BackgroundQuery:=False
End With
'Renommage et suppression des Feuilles
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "Rapport 1"
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
'Sheets("Liste_All_Masques").Select
'ActiveWindow.SelectedSheets.Delete
'Sauvegarde du fichier en format .xlsx
ActiveWorkbook.SaveAs FileName:= _
"W:\Ateliers\PHOTO\Masks\Reports_TGV_IRETICLE\Liste_All_Masques.xlsx" _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
'Sauvegarde du fichier sans afficher la fenêtre de confirmation
ActiveWorkbook.Close savechanges:=True
'Allow confirmation windows to appear as normal
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Msgbox "Update fait"
End Sub
出现此问题的原因可能是,当 Workbook_Open 事件触发时,Excel 中的某些对象和进程未完全初始化。具体来说,在工作簿打开时添加 Power Query 查询(如 ActiveWorkbook.Queries.Add)可能会导致 Excel 行为不可预测,因为某些依赖项或加载项完全加载可能为时过早。
以下是一些有助于解决此问题的调整:
在工作簿打开后添加延迟:如果您还没有尝试过此操作,请在工作簿打开后引入延迟。尝试在添加查询之前延迟的这个版本的代码:
Private Sub Workbook_Open()
Application.OnTime Now + TimeValue("00:00:02"), "RunAfterOpen"
End Sub
Private Sub RunAfterOpen()
' Place the entire Workbook_Open code here...
End Sub
在 Power Query 设置中禁用后台刷新:由于 Workbook_Open 中的 Power Queries 可能会导致冲突,因此设置 .BackgroundQuery = False (您已经拥有)。这可能会减少与时间相关的问题。
使用DoEvents:在添加查询之前,插入DoEvents以让Excel完成任何挂起的操作。例如,在添加查询的行之前添加 DoEvents:
DoEvents
ActiveWorkbook.Queries.Add Name:="Liste_All_Masques", Formula:= _
"let" & Chr(13) & ...