Skip to content

Instantly share code, notes, and snippets.

@nanbu
Created August 31, 2011 12:38
Show Gist options
  • Save nanbu/1183436 to your computer and use it in GitHub Desktop.
Save nanbu/1183436 to your computer and use it in GitHub Desktop.
VBAで文字コードを指定して文字列をテキストファイルに保存 (Windows専用)

Function SaveText(Filename, Text As String, Optional Encoding = "UTF-8") As Boolean

  • 文字コードを指定して文字列をテキストファイルに保存します。
  • WindowsのVBAでのみ動作します。(MacのVBAではエラーが発生します)
  • UTF-8で出力する場合はBOMなしのUTF-8(別名「UTF-8N」)にしています。

特徴

  • ファイルのオープン・クローズ処理が不要です(関数の内部で完結しています)。
  • UTF-8はBOMなしにしていますのでHTML等のWeb用途に向いています。

使用例

SaveText("Hello.txt", "こんにちは", "shift_jis")

引数と戻り値

  • Filename: テキストファイルの保存先パス
  • Text: 保存する文字列
  • Encoding: テキストファイルの文字コード。省略可。ADODB.StreamのCharsetプロパティが対応している文字セットを指定する。省略時はUTF-8になる。
  • 戻り値: 保存が成功したらTrue、失敗したらFalseを返す

一般的にEncodingに指定する文字とその詳細

一般的にEncodingに指定する文字とその詳細

  • "utf-8" → UTF-8(BOMなし)
  • "utf-16" → UTF-16LE
  • "shift_jis" → CP932(WindowsのShift_JIS)
Function SaveText(Filename, Text As String, Optional Encoding = "UTF-8") As Boolean
Const adTypeBinary = 1
Const adTypeText = 2
Const adSaveCreateOverWrite = 2
Dim Position
Dim Charset As String
Dim Bytes
Position = 0
Select Case UCase(Encoding)
Case "UTF-8"
Charset = "utf-8"
Position = 3
Case Else
Charset = Encoding
End Select
On Error Resume Next
With CreateObject("ADODB.Stream")
.Type = adTypeText
.Charset = Charset
.Open
.WriteText Text
.Position = 0
.Type = adTypeBinary
.Position = Position
Bytes = .Read
.Close
End With
With CreateObject("ADODB.Stream")
.Type = adTypeBinary
.Open
.Position = 0
.Write Bytes
.SaveToFile Filename, adSaveCreateOverWrite
.Close
End With
If Err.Number = 0 Then
SaveText = True
Else
SaveText = False
End If
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment