以前書いたファイルのBase64エンコード・デコード処理を行うVBAマクロをメモとして残しておきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | Option Explicit Public Sub Sample() Sheet1.TextBox1.Text = EncodeBase64( "C:\Test\Sample.pdf" ) Debug.Print DecodeBase64(Sheet1.TextBox1.Text, "C:\Test\Sample_Decode.pdf" ) End Sub Private Function EncodeBase64( ByVal FilePath As String ) As String 'ファイルをBase64エンコード Dim elm As Object Dim ret As String Const adTypeBinary = 1 Const adReadAll = -1 ret = "" '初期化 On Error Resume Next Set elm = CreateObject( "MSXML2.DOMDocument" ).createElement( "base64" ) With CreateObject( "ADODB.Stream" ) .Type = adTypeBinary .Open .LoadFromFile FilePath elm.DataType = "bin.base64" elm.nodeTypedValue = .Read(adReadAll) ret = elm.Text .Close End With On Error GoTo 0 EncodeBase64 = ret End Function Private Function DecodeBase64( ByVal Base64Str As String , ByVal FilePath As String ) As Long 'ファイルをBase64デコード Dim elm As Object Dim ret As Long Const adTypeBinary = 1 Const adSaveCreateOverWrite = 2 ret = -1 '初期化 On Error Resume Next Set elm = CreateObject( "MSXML2.DOMDocument" ).createElement( "base64" ) elm.DataType = "bin.base64" elm.Text = Base64Str With CreateObject( "ADODB.Stream" ) .Type = adTypeBinary .Open .Write elm.nodeTypedValue .SaveToFile FilePath, adSaveCreateOverWrite .Close End With If Err.Number <> 0 Then ret = 0 On Error GoTo 0 DecodeBase64 = ret End Function |
上記の通り、エラー処理は適当です。
この記事へのコメントはありません。