I want to create a file using VBA, but have the following three requirements.
- The file contents are unicode
- The filename is unicode
- I want to append to an existing file (if the file exists, otherwise to create it)
I present here two extracts of code. The first extract will do 1 and 2. The second extract will do 1 and 3. However I can't figure out how to do 1, 2 and 3.
I can use the following code from GSerg's answer in How can I create text files with special characters in their filenames to create a unicode filename with unicode contents
Private Declare Function CreateFileW Lib "kernel32.dll" (ByVal lpFileName As Long, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByRef lpSecurityAttributes As Any, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long
Private Declare Function WriteFile Lib "kernel32.dll" (ByVal hFile As Long, ByRef lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, ByRef lpNumberOfBytesWritten As Long, ByRef lpOverlapped As Any) As Long
Private Const CREATE_ALWAYS As Long = 2
Private Const OPEN_ALWAYS As Long = 4
Private Const GENERIC_WRITE As Long = &H40000000
Sub writeLine(aFile As String, val As String)
Dim hFile As Long
hFile = CreateFileW(StrPtr(aFile), GENERIC_WRITE, 0, ByVal 0&, OPEN_ALWAYS, 0, 0)
WriteFile hFile, &HFEFF, 2, 0, ByVal 0& 'Unicode byte order mark (not required, but to please Notepad)
WriteFile hFile, ByVal StrPtr(val), Len(val) * 2, 0, ByVal 0&
CloseHandle hFile
End Sub
I can use the following code to append to a non-unicode fillename with unicode contents
Sub AddToFile(ByVal aFile As String, ByVal aLine As String)
Dim myFSO2 As New Scripting.FileSystemObject
Dim ts2 As TextStream
Set ts2 = myFSO2.OpenTextFile(aFile, ForAppending, True, TristateTrue)
ts2.Write aLine & vbNewLine
ts2.Close
End Sub
How can I adapt either extract of code (or do something else) to append to a Unicode filename with Unicode contents?
(I read about using SetFilePointer with regard to the first extract of code but I couldn't get it to work)
UPDATE
The problem probably lies with the population of the aFile
variable. (Thanks @ChipsLetten) I populate it as follows
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open(fileToOpen)
For Each para In WordDoc.Paragraphs
If para.Style.NameLocal = "Style1" Then
aFile= para.Range.Text