PDA

View Full Version : SaveAs2 fileformat/encoding not working ???



bjasen
09-17-2020, 02:42 AM
Hi all

From a VBA macro in Excell I'm trying to open a .docx file and save it as a .txt file using word application.

My problem is that the saved .txt file is not plain readable text.
I have tried to record a macro in word to check how that would look and it too uses the SaveAs2 command. When running the macro in word a .txt file is generated and the contens is OK, but when done from Excell the file is generated but the contents is not correct.

Any idears on what I'm missing?

BR
Bjasen


The 2 macroes are:

Macro from Word (working):
Sub SaveDocxtoTxt()
ChangeFileOpenDirectory "C:\Users\bjaj\Documents"
ActiveDocument.SaveAs2 FileName:="text_file_3_lines.txt", FileFormat:= _
wdFormatText, LockComments:=False, Password:="", AddToRecentFiles:=False, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, Encoding:=1252, InsertLineBreaks:=False, AllowSubstitutions:=False _
, LineEnding:=wdCRLF, CompatibilityMode:=0
End Sub



Macro from excell (not working - wrong format/encoding):
Sub Change_file_to_txt()
Dim WordApp As Object
Dim strDocName As String
Dim intPos As Integer

' Open word and file
Set WordApp = CreateObject("Word.Application")
WordApp.Documents.Open Filename:="C:\Users\bjaj\Documents\text_file_3_lines.docx"

' Strip off extension and add ".txt" extension
strDocName = WordApp.ActiveDocument.FullName
intPos = InStrRev(strDocName, ".")
strDocName = Left(strDocName, intPos - 1)
strDocName = strDocName & ".txt"

' Save file in new format with new extension
WordApp.ActiveDocument.SaveAs2 Filename:=strDocName, FileFormat:= _
wdFormatText, LockComments:=False, Password:="", AddToRecentFiles:=False, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, Encoding:=1252, InsertLineBreaks:=False, AllowSubstitutions:=False _
, LineEnding:=wdCRLF, CompatibilityMode:=0

' Exit word
WordApp.Quit SaveChanges:=wdDoNotSaveChanges
Set WordApp = Nothing
End Sub

p45cal
09-19-2020, 09:51 AM
Excel won't know that wdFormatText is 2 and wdCRLF is 0, an that wdDoNotSaveChanges is also 0, so substitute those bits for the numbers.

bjasen
09-21-2020, 07:26 AM
Hi p45cal. It all make sense now :yes
Thanks

DanWall
07-31-2021, 07:34 PM
Excel won't know that wdFormatText is 2 and wdCRLF is 0, an that wdDoNotSaveChanges is also 0, so substitute those bits for the numbers.

I had a similar issue - looking at your reply, I realised I had just copied my Word VBA code straight to Excel without even thinking about converting the the constants - thank you so much for this.

:banghead: