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.

VBAを使用して今の日時をファイル名にして出力する方法

Last updated at Posted at 2023-04-19

結論

Sub ExportData()
    Dim fileName As String
    Dim currentTime As String
    Dim data() As Variant
    Dim i As Long, j As Long
    Dim numRows As Long, numCols As Long
    Dim ws As Worksheet
    
    ' エクスポートするデータを配列に格納する(ここでは、Sheet1のA1:B10の範囲)
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    With ws
        numRows = .Range("A1:B10").Rows.Count
        numCols = .Range("A1:B10").Columns.Count
        data = .Range("A1").Resize(numRows, numCols).Value
    End With
    
    ' ファイル名を設定する
    currentTime = Format(Now(), "yyyy-mm-dd_hh-mm-ss")
    fileName = "export_" & currentTime & ".csv"
    
    ' データをCSVファイルとしてエクスポートする
    With CreateObject("Scripting.FileSystemObject").CreateTextFile(fileName, True)
        For i = 1 To numRows
            For j = 1 To numCols
                .Write data(i, j)
                If j < numCols Then .Write ","
            Next j
            .WriteLine
        Next i
        .Close
    End With
    
    ' 完了メッセージを表示する
    MsgBox "データをファイル " & fileName & " にエクスポートしました。"
End Sub

解説

上記のVBAコードでは、Now()関数を使用して現在の日時を取得し、Format()関数を使用してファイル名に含めるためのフォーマットを指定しています。また、CreateTextFile()メソッドを使用して新しいファイルを作成し、データをCSV形式で出力しています。最後に、MsgBox関数を使用して完了メッセージを表示しています。

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?