■ はじめに
* JavaのプロパティファイルをExcelで管理したい場合に Excelからプロパティファイルを出力するマクロを組んでみた
■ サンプル
Sub CreatePropertyFileButton_Click()
' 定数
Const MaxRow As Integer = 5000
Const MaxColumn As Integer = 5000
Dim sheet As Worksheet
Set sheet = Worksheets("Message")
fileName = "Message.properties"
Dim propertyContent As String: propertyContent = ""
propertyContent = propertyContent & "#############################################" & vbCrLf
propertyContent = propertyContent & "# Property File For Messages #" & vbCrLf
propertyContent = propertyContent & "#############################################" & vbCrLf
propertyContent = propertyContent & vbCrLf
For i = 2 To MaxColumn
If IsEmpty(sheet.Cells(i, 1).Value) = True Then
' 値がない時は処理を中断
Exit For
End If
If IsEmpty(sheet.Cells(i, 3).Value) = False Then
' コメントがある場合、設定する
propertyContent = propertyContent & "# " & sheet.Cells(i, 3).Value & vbCrLf
End If
propertyContent = propertyContent & sheet.Cells(i, 1).Value & "=" & sheet.Cells(i, 2).Value & vbCrLf
Next
If SaveFileWithUtf8(propertyContent, fileName) = False Then
MsgBox "ファイルの作成に失敗しました", vbCritical & vbOKOnly, "エラー"
End If
End Sub
Public Function SaveFileWithUtf8(ByVal inputData As String, ByVal fileName As String) As Boolean
On Error GoTo ErrorHandler
Dim isSuccessful As Boolean: isSuccessful = False
' 定数
Const AdodbTypeBinary As Integer = 1
Const AdodbTypeText As Integer = 2
Const AdodbSaveCreateOverWrite As Integer = 2
Const FileCharset As String = "UTF-8"
' ADODB.Streamを作成
Dim sourceOfDataStream: Set sourceOfDataStream = CreateObject("ADODB.Stream")
' 最初はテキストモードでUTF-8で書き込む
sourceOfDataStream.Type = AdodbTypeText
sourceOfDataStream.Charset = FileCharset
sourceOfDataStream.Open
' ファイルに書き込み
sourceOfDataStream.WriteText (inputData), 1
' バイナリモードにするためにPositionを0に戻す
' Readするためにはバイナリタイプでないといけない
sourceOfDataStream.Position = 0
sourceOfDataStream.Type = AdodbTypeBinary
' Positionを3にしてから読み込むことで最初の3バイトをスキップする
' UTF-8(BOMあり)のBOMをスキップします
sourceOfDataStream.Position = 3
Dim binaryOutputData: binaryOutputData = sourceOfDataStream.Read()
' 読み込んだバイナリデータをバイナリデータとしてファイルに出力する
Dim outputStream: Set outputStream = CreateObject("ADODB.Stream")
outputStream.Type = AdodbTypeBinary
outputStream.Open
outputStream.Write (binaryOutputData)
outputStream.SaveToFile fileName, AdodbSaveCreateOverWrite
isSuccessful = True
GoTo Finally
ErrorHandler:
MsgBox Err.Number & ":" & Err.Description, vbCritical & vbOKOnly, "エラー"
isSuccessful = False
Finally:
'ストリームの後始末
If Not outputStream Is Nothing Then
outputStream.Close
End If
If Not sourceOfDataStream Is Nothing Then
sourceOfDataStream.Close
End If
SaveFileWithUtf8 = isSuccessful
End Function
入力データ : シート「Message」
IDs Message Comments E00001 入力誤りです ユーザからの入力値に誤りがある場合 I00001 インフォです
出力結果 : Message.properties
# Property File For Messages # # ユーザからの入力値に誤りがある場合 E00001=入力誤りです I00001=インフォです
関連記事
Excel マクロ ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2015/07/15/104500