Base64にエンコード

Base64にエンコードする。

VBAで指定した文字列をBase64の形式にエンコードします。
エンコードには「Msxml2.DOMDocument.3.0」と「ADODB.Stream」のオブジェクトを利用してエンコードをしています。

動作確認
Windows10/Excel2016:○
Windows11/Excel2024:○

デコードの方法はこちらのサイトに掲載しています。
 「Base64をデコードする」 

'******************************************************************************
' Base64にエンコード
'******************************************************************************
Sub Main_StirngToBase64()

    Dim sEncode As String
    sEncode = "吾輩は猫である"
    
    Debug.Print "(エンコード前)"
    Debug.Print sEncode
    Debug.Print
    Debug.Print "(エンコード後)"
    Debug.Print encodeToBase64(sEncode)

End Sub

'******************************************************************************
' Base64エンコード
'------------------------------------------------------------------------------
'  第1引数:Base64に変換する文字列
'******************************************************************************
Function encodeToBase64(getText As String) As String

    'DOMDocumentオブジェクトの作成
    Dim oXmlNode  As Object
    Set oXmlNode = CreateObject("Msxml2.DOMDocument.3.0").createElement("base64")
    
    'データタイプにbin.base64を設定
    oXmlNode.dataType = "bin.base64"
    
    '引数の文字列をBASE64に変換
    oXmlNode.nodeTypedValue = convStringToBinary(getText)
    
    '変換結果を返す
    encodeToBase64 = oXmlNode.text
    
    Set oXmlNode = Nothing
  
End Function

'******************************************************************************
' 文字列をバイナリに変換
'------------------------------------------------------------------------------
'  第1引数:文字列
'******************************************************************************
Function convStringToBinary(getText As String) As Variant
    
    'ADODB.Streamオブジェクトの作成
    Dim oAdoStm As Object
    Set oAdoStm = CreateObject("ADODB.Stream")
  
    'データ型を設定(2:テキストデータ)
    oAdoStm.Type = 2
    
    '文字コードを指定
    oAdoStm.Charset = "utf-8" 'or "shift_jis"
    
    'オブジェクトにテキストデータを書き込む。
    oAdoStm.Open
    oAdoStm.WriteText getText
    
    'オブジェクト内の位置を設定
    oAdoStm.Position = 0
    
    'データ型を設定(1:バイナリデータ)
    oAdoStm.Type = 1
    
    'データを戻り値として返す
    convStringToBinary = oAdoStm.Read
    
    Set oAdoStm = Nothing

End Function

 ■実行結果