0

I want that all my files be saved in unicode or utf-8 format and not ANSI.

Here is the code:

Sub cvelle()
Dim iRow As Long
Dim iFile As Integer
Dim sPath As String
Dim sFile As String


For iRow = 1 To Cells(Rows.Count, "B").End(xlUp).Row
    iFile = FreeFile
    With Rows(iRow)
        sPath = "E:\" & .Range("B1").Value & "\"
        If Len(Dir(sPath, vbDirectory)) = 0 Then MkDir sPath
        sFile = .Range("D1").Value & ".txt"
        
        Open sPath & sFile For Output As #iFile
        Print #iFile, .Range("E1").Value
        Close #iFile
    End With
Next iRow
End Sub

Now, I thought that just inserting the code below would be enough.

sFile = .Range("D1").Value & ".txt",FileFormat:= _xlUnicodeText

But it gives me an error.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Stefan89BEG
  • 129
  • 2
  • 4
  • 17
  • Use ```FileSystemObject```, example [see here](http://stackoverflow.com/questions/14261632/how-can-i-create-text-files-with-special-characters-in-their-filenames). – Daniel Dušek Jun 19 '15 at 08:14
  • How about reading this post : http://software-solutions-online.com/2014/03/13/excel-vba-save-file-dialog-getsaveasfilename/ – keong kenshih Jun 19 '15 at 08:22
  • 2
    There's a brilliant post at: http://stackoverflow.com/questions/12352958/excel-vba-export-to-utf-8 which gets around Excels mongrel unicode exporting and uses true Utf-8 via ODBC – Trum Jun 19 '15 at 08:30
  • Thank you! I will check it out! – Stefan89BEG Jun 19 '15 at 08:33
  • Just to make sure that we all on the same page, the text that I want to insert in .txt is already unicode, I just want to make in Notepad default SavaAs type= unicode..because there is a loss of some characters.. thanks! – Stefan89BEG Jun 19 '15 at 08:35
  • Hi @Stefan89BEG, when you export from Excel in Unicode it tends to be UTF-16 unless you do it this way. I had a bit of a time of it trying to move bulk data to MySQL and the above method definitely saves as the right type – Trum Jun 19 '15 at 09:49

5 Answers5

0

I know how to create a uncode txt file. Maybe you can try read data into variable > create a uncode txt > write data into txt >save txt

Dim fso As Object, myTxtFile As ObjectSet 
   fso = CreateObject("Scripting.FileSystemObject")
   Set myTxtFile = fso.CreateTextFile(fileName:="c:\123.txt", OverWrite:=True, Unicode:=True)
陳彥錡
  • 1
  • 1
0
Function SaveTextToFile(ByVal txt$, ByVal filename$, Optional ByVal encoding$ = "windows-1251") As Boolean
    ' function saves text in txt in filename$
    On Error Resume Next: Err.Clear
    Select Case encoding$

        Case "windows-1251", "", "ansi"
            Set FSO = CreateObject("scripting.filesystemobject")
            Set ts = FSO.CreateTextFile(filename, True)
            ts.Write txt: ts.Close
            Set ts = Nothing: Set FSO = Nothing

        Case "utf-16", "utf-16LE"
            Set FSO = CreateObject("scripting.filesystemobject")
            Set ts = FSO.CreateTextFile(filename, True, True)
            ts.Write txt: ts.Close
            Set ts = Nothing: Set FSO = Nothing

        Case "utf-8noBOM"
            With CreateObject("ADODB.Stream")
                .Type = 2: .Charset = "utf-8": .Open
                .WriteText txt$

                Set binaryStream = CreateObject("ADODB.Stream")
                binaryStream.Type = 1: binaryStream.Mode = 3: binaryStream.Open
                .Position = 3: .CopyTo binaryStream        'Skip BOM bytes
                .flush: .Close
                binaryStream.SaveToFile filename$, 2
                binaryStream.Close
            End With

        Case Else
            With CreateObject("ADODB.Stream")
                .Type = 2: .Charset = encoding$: .Open
                .WriteText txt$
                .SaveToFile filename$, 2        ' saving in coding that you need
                .Close
            End With
    End Select
    SaveTextToFile = Err = 0: DoEvents
End Function
DiegoB
  • 1
  • 2
  • 1
    It would be helpful if you edited the answer to explain how and why this is a good solution. – Dragonthoughts Jun 11 '20 at 12:34
  • to be on the same page ,topic starter had issues with saving i posted universal script that could be used with many formats koi8-r, ascii, utf-7, utf-8, utf-8noBOM, utf-16, Windows-1251, unicode you can check full list HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Charset – DiegoB Jun 11 '20 at 14:06
  • 1
    I meant t edit the answer, not add a comment, so that future readers would understand it. I am the author of a paper on character set recognition in hostile environments, published by the Unicode Consortium. – Dragonthoughts Jun 12 '20 at 08:24
0

i personally use it at work because some pl reports have whole bunch of formats and tomake anadjustment you need it here is a function to read ```

Function LoadTextFromTextFile(ByVal filename$, Optional ByVal encoding$) As String
    ' functions loads in code  Charset$ from filename$
    On Error Resume Next: Dim txt$
    If Trim(encoding$) = "" Then encoding$ = "windows-1251"
    With CreateObject("ADODB.Stream")
        .Type = 2:
        If Len(encoding$) Then .Charset = encoding$
        .Open
        .LoadFromFile filename$        'load data from file 
        LoadTextFromTextFile = .ReadText        ' read text
        .Close
    End With
End Function
DiegoB
  • 1
  • 2
0

Hope this might save someone some time:

Sub ExportToTxt()
    Dim fileStream As Object
    Set fileStream = CreateObject("ADODB.Stream")
    fileStream.Charset = "utf-8"
    fileStream.Open

    Dim rangeToExport As Range
    Set rangeToExport = Worksheets("BPC-Processed").Range("A1").CurrentRegion

    Dim firstCol, lastCol, firstRow, lastRow As Integer
    firstCol = rangeToExport.Columns(1).Column
    lastCol = firstCol + rangeToExport.Columns.Count - 1
    firstRow = rangeToExport.Rows(1).row
    lastRow = firstRow + rangeToExport.Rows.Count - 1

    Dim r, c As Integer
    Dim str As String
    Dim delimiter As String
    For r = firstRow To lastRow
        str = ""
        For c = firstCol To lastCol
            If c = 1 Then
                delimiter = ""
            Else
                delimiter = vbTab ' tab
            End If
            str = str & delimiter & rangeToExport.Cells(r, c).Value
        Next c
        fileStream.WriteText str & vbCrLf ' vbCrLf: linebreak
    Next r

    Dim filePath As String
    filePath = Application.ThisWorkbook.Path & "\BPC-Processed.txt"
    fileStream.SaveToFile filePath, 2 ' 2: Create Or Update
    fileStream.Close
End Sub
Rohim Chou
  • 907
  • 10
  • 16
-1

Instead of typing a bunch of code, I figured out to make as default encoding as unicode here is how:

 1. Right click -> New -> Text Document 
 2. Open "New Text Document.txt". Do NOT type anything! 
 3. Go to "File -> Save As... " and choose UniCode under "Encoding:", press     "Save" and overwrite existing file. Close the file. 
 4. Rename "New Text Document.txt" to "UniCode.txt" 
 5. Copy "UniCode.txt" to "C:\WINDOWS\SHELLNEW" 
 6. Open Regedit and Navigate to HKEY_CLASSES_ROOT\.txt\ShellNew 
 7. Right click in the right window -> New -> "String Value" and rename it to  "FileName". 
 8. Double click on "FileName" and put "UniCode.txt" into "Value Data". 
 9. press OK It's finished. 

Thanks to all!

Stefan89BEG
  • 129
  • 2
  • 4
  • 17
  • How can we do this with VBA?(editing Registery as above) – mgae2m Jul 20 '17 at 00:28
  • 1
    This forces the entire system to use a text file with the [Unicode BOM](https://en.wikipedia.org/wiki/Byte_order_mark) saved in it as the template for all plain-text files created by the shell. Arguably, you should not do that even to your own computer; most certainly [not to other people's computers](https://devblogs.microsoft.com/oldnewthing/20081211-00/?p=19873). Also note that this does not magically ensure that Unicode data will be saved in the file when you type. It is only *likely* to happen *if* the end program looks for the BOM. Notepad does. – GSerg Aug 06 '20 at 13:34