0
2

More than 5 years have passed since last update.

【VBA】ダイアログを使ってファイルに名前をつけて保存する

Posted at

VBA初心者では苦労したので備忘録。

何を作りたかったのか

Excelで入力された情報を元にCSVファイルを出力。
その際にファイルダイアログを表示して任意でファイル名を選択できる。
デフォルトファイル名はしっかり入る……という単純なもの。
失敗したのはダイアログで選ぶからと思いFileDialog関数に注力してしまった点。
FileDialogでも「名前を付けて保存」はあるのだが……今回の要件は満たせなかった。

出来上がったコード

OutputCSV.xslx
Sub OutputCSV()

    '変数宣言
    Dim filePath As Variant
    Dim DirPath As String
    Dim fileNo As Integer

    'ファイルパスを選択する
    Filename = "test_file.csv"
    DirPath = ThisWorkbook.Path
    filePath = Application.GetSaveAsFilename(DirPath & "\" & Filename, "CSV(カンマ区切り)(*.csv),*.csv")
    If filePath = False Then
        Exit Sub
    End If

    '初期値設定
    fileNo = FreeFile 'FreeFile関数で使用可能なファイル番号取得

    'ファイル開く
    Open filePath For Output As #fileNo

    '----------------------------------------
    ' CSV出力
    '----------------------------------------
    Write #fileNo, Cells(1, 1), Cells(1, 2), Cells(1, 3)

    'ファイル閉じる
    Close #fileNo

    MsgBox "CSVを出力しました"
End Sub
0
2
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
2