目標は、ワークブックを開き、.csv ファイルをインポートし、書式設定を実行し、保存して Excel を終了するという日常のタスクを自動化することです。唯一の要件は、コンピューターの電源が入っていることです。Windows タスク スケジューラを使用して、マクロが有効になっているワークブックを毎日開いています。このサイトの助けを借りて、引数 /p "my specific path" をタスクに追加して、アクセスしたいインポート パスを設定しました。次に、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