' Written: January 21, 2018
' Authpor: Leith Ross
' Summary: Copies all of the cells in the supplied range with
' values to a new Unicode text file. Each row is terminated
' with the specified new line character(s) and the fields
' in each row are separated with the character(s) in the
' string separator.
'
' NOTE: If you open this file with Excel, you will need to run
' TextToColumns to separate the data into the worksheet columns.
Private Declare PtrSafe Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Sub CreateUnicodeFile(ByVal File As String, ByRef Rng As Range, Optional Separator As String, Optional NewLine As String)
Dim Bytes() As Byte
Dim Divider As String
Dim k As Integer
Dim n As Long
Dim Row As Long
Dim Text As String
' Defaults: Separator = ",", NewLine = CrLf
Separator = IIf(Separator = "", ",", Separator)
NewLine = IIf(NewLine = "", vbCrLf, NewLine)
' Add the Unicode Byte Order Mark for little-endian.
ReDim Bytes(1)
Bytes(0) = 255
Bytes(1) = 254
For Row = 1 To Rng.Rows.Count
For Col = 1 To Rng.Columns.Count
Text = Text & Rng.Cells(Row, Col)
If Col <> Rng.Columns.Count Then
Text = Text & Separator
End If
Next Col
Text = Text & NewLine
Next Row
Text = StrConv(Text, vbUnicode)
n = Len(Text)
k = UBound(Bytes)
ReDim Preserve Bytes(k + n)
CopyMemory Bytes(k + 1), ByVal Text, n
Open File For Binary Access Write As #1
Put #1 , , Bytes
Close #1
End Sub