VBAでExcelの特定範囲をCSV出力(UTF-8)
Author: 水卜
Author: 水卜
Excelの特定範囲をCSVとして出力するVBAマクロ。
変数startRow, startCol, lastRow, lastColに囲まれた範囲を対象とする。
引数化するなりして使ってください。
Function exportCsv(ByVal filename As String)
Dim lastRow As Long, row As Long, lastCol As Integer, col As Integer
Dim fileNumber As Integer, csvFile As Variant
csvFile = filename
startRow = 1
startCol = 1
lastRow = 15
lastCol = 15
Dim adoSt As Object
Set adoSt = CreateObject("ADODB.Stream")
Dim strLine As String
With adoSt
.Charset = "UTF-8"
.Open
For row = startRow To lastRow
strLine = ""
For col = startCol To lastCol - 1
Debug.Print Cells(row, col).Value
Dim replacedString As String
replacedString = Replace(Cells(row, col).Value, vbLf, "\r\n")
strLine = strLine & """" & replacedString & """" & ","
Next
strLine = strLine & Cells(row, col) & """"
.WriteText strLine, 1
Next
.SaveToFile csvFile, 2
.Close
End With
MsgBox "出力:" & csvFile
End Function