Search code examples
excelvbatextboxuserform

VBA Textbox to UTF-8 Textfile


I got a VBA Script to save the input from a UserForm Textbox to a Textfile. The Problem is that it's saving it in ANSI coding and not UTF-8.

Is there a way to change this?

Here is my code:

Private Sub CommandButton1_Click()
Call WriteFile("C:\Zuschauer.txt", TextBox1)
End Sub

Sub WriteFile(ByRef Path As String, ByRef Text As String)
  Dim FileNr As Long
  FileNr = FreeFile
  Open Path For Output As #FileNr
  Print #FileNr, Text;
  Close #FileNr
End Sub

Solution

  • The code below uses ADODB.Stream so you'll need to add a reference in your project to Microsoft Active Data Objects 6.1 Library (versions other than 6.1 may also work).

    Sub WriteUnicodeUTF8File(ByVal FileSpec As String, ByVal data As String)
        With New ADODB.Stream
            .Type = adTypeText
            .Charset = "UTF-8"
            .Open
            .WriteText data
            .SaveToFile FileSpec, adSaveCreateOverWrite
            .Close
        End With
    End Sub
    

    Depending on your particulars you may need to choose different options such as adSaveCreateOverWrite.