【Excel】保存と同時にCSV出力する

DEVELOP, Excel, Windows

上書き保存時も対象。全てのシートを出力する。

' CSVファイルの出力
Sub OutputCSV()
 
Dim Ws As Worksheet
Set Ws = ThisWorkbook.Worksheets(1)
 
Dim csvFile As String
csvFile = ActiveWorkbook.Path & "/" & ActiveSheet.Name & ".csv"
 
Open csvFile For Output As #1
 
Dim i As Long, j As Long
i = 1
 
Do While Ws.Cells(i, 1).Value <> ""
    j = 1
    Do While Ws.Cells(i, j + 1).Value <> ""
        Print #1, Ws.Cells(i, j).Value & ",";
        j = j + 1
    Loop
    Print #1, Ws.Cells(i, j).Value & vbCr;
    i = i + 1
Loop 
Close #1
End Sub
' ファイルを保存時
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim Ws As Worksheet
        For Each Ws In Worksheets
            Ws.Activate
            OutputCSV
    Next Ws
End Sub

Posted by kazupon