0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【個人メモ】コマンド生成してテキストファイルに出力するマクロ

0
Posted at

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?