目标是自动执行日常任务以打开工作簿、导入 .csv 文件并执行一些格式化、保存和退出 excel,唯一的要求是打开计算机。我每天使用 Windows 任务计划程序打开启用宏的工作簿。在此站点的帮助下,我将参数 /p“我的特定路径”添加到任务中以设置我希望访问的导入路径。然后,使用 Workbook_open 函数执行导入,但是在突出显示 .refresh backgroundquery:=false 行时出现以下错误:
Run-time error '1004':
Excel cannot find the text file to refresh this external data range.
Check to make sure the text file has not been moved or renamed, then try
the refresh again.
现在,如果我选择“结束”来停止调试器并自己运行宏,一切正常。路径在网络上,如果这很重要的话。如果有帮助,我可以发布部分代码,但它很长。不用说我不是 VBA 高手,所以我将代码拼凑在一起,但除了 .csv 文件的初始导入之外,一切正常。提前感谢您的任何建议。
相关代码:
R = 1
FName = Dir(Path & DayTime & ".csv")
Do While FName <> ""
ImportCsvFile FName, ActiveSheet.Cells(R, 1)
R = ActiveSheet.UsedRange.Rows.count + 1
DayTime = DayTime + 1
FName = Dir(Path & DayTime & ".csv")
Loop
Sub ImportCsvFile(FileName As Variant, Position As Range)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & FileName _
, Destination:=Position)
.Name = Replace(FileName, ".csv", "")
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlMacintosh
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = ","
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
End With
End Sub