chatgptが作った
動作確認未実施
Sub WriteCommandsToFileWithOverwriteCheck()
Dim cellValue As String
Dim commandText As String
Dim filePath As String
Dim fileNum As Integer
Dim i As Integer
Dim lastRow As Integer
Dim overwrite As VbMsgBoxResult
' 出力先として指定するフルパスをセルA1から取得
filePath = ThisWorkbook.Sheets(1).Range("A1").Value
' もしセルが空の場合のエラーハンドリング
If filePath = "" Then
MsgBox "セルA1に有効なファイルパスを入力してください。", vbExclamation
Exit Sub
End If
' ファイルパスに拡張子が含まれていなければ、".txt"を追加
If LCase(Right(filePath, 4)) <> ".txt" Then
filePath = filePath & ".txt"
End If
' ファイルが既に存在するか確認
If Dir(filePath) <> "" Then
' ファイルが存在する場合、上書き確認ダイアログを表示
overwrite = MsgBox(filePath & " は既に存在します。上書きしますか?", vbYesNo + vbExclamation, "上書き確認")
If overwrite = vbNo Then
MsgBox "処理をキャンセルしました。"
Exit Sub
End If
End If
' テキストファイルを開く
fileNum = FreeFile
On Error GoTo ErrorHandler ' ファイルオープン時のエラーハンドリング
Open filePath For Output As fileNum
' ここからファイルに随時コマンドを出力
' 例として、B列にあるデータをコマンドとして書き込む
lastRow = ThisWorkbook.Sheets(1).Cells(Rows.Count, 2).End(xlUp).Row ' B列の最終行の取得
For i = 1 To lastRow
cellValue = ThisWorkbook.Sheets(1).Cells(i, 2).Value
commandText = "echo " & cellValue & " > output.txt"
' コマンドをファイルに書き込む
Print #fileNum, commandText
Next i
' ファイルを閉じる
Close fileNum
MsgBox "コマンドを保存しました: " & filePath
Exit Sub
ErrorHandler:
MsgBox "ファイルを開く際にエラーが発生しました。パスを確認してください。", vbCritical
Close fileNum
End Sub