Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save as .txt in vba

I am looking to have my Macro save a new sheet that i created as a .txt file. this is the code i have so far.

Sub Move()  
'  
' Move Macro  
'  
' Keyboard Shortcut: Ctrl+m  
'  
Sheets("Sheet1").Select  
Range("A1").Select  
Range(Selection, Selection.End(xlToRight)).Select  
Range(Selection, Selection.End(xlDown)).Select  
Selection.Copy  
Workbooks.Add  
ActiveSheet.Paste  

ActiveWorkbook.SaveAs Filename:="e:" & _
"HDR" + Format(Now(), "YYYYMMDDhhmmss") & ".txt"

End Sub

That includes my macro. I am having trouble with the last part where it saves as a .txt file.
I am currently getting a bunch of crap on my .txt file, here is an example,
"PK ! !}ñU{ Š [Content_Types].xml ¢(  ÌTÝNÂ0¾7ñ–Þš­€‰1†Á…⥒ˆPÚ3¶ÐµMOÁñöž•Ÿ¨".
Any help would be great.

like image 911
Tony Bergeson Avatar asked Oct 01 '14 21:10

Tony Bergeson


2 Answers

Manually changing the extension of the file name does not actually change the file type. The SaveAs method takes a file type argument. The code you want is

ActiveWorkbook.SaveAs Filename:="e:" & "HDR" + Format(Now(), "YYYYMMDDhhmmss") _
& ".txt", FileFormat:= xlTextWindows

Doing a search from within Excel help for XlFileFormat will get you (almost) the full list of possible file formats, including 6 text formats, and 4 CSV formats.

like image 54
Degustaf Avatar answered Sep 18 '22 09:09

Degustaf


Adding txt to the name does not automatically encode the word document into plain text format.

Instead attempt

ActiveWorkbook.SaveAs Filename:="e:" & _
"HDR" + Format(Now(), "YYYYMMDDhhmmss") & ".txt", FileFormat:=wdFormatText, Encoding:=1252
like image 38
AJY Avatar answered Sep 22 '22 09:09

AJY