如何在vba中保存为.txt

时间:2014-10-01 21:32:06

标签: excel vba excel-formula excel-2010

我希望让我的宏保存一个我创建为.txt文件的新工作表。这是我到目前为止的代码。

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

那包括我的宏。我在将其保存为.txt文件的最后一部分时遇到问题 我目前在我的.txt文件上得到了一堆废话,这是一个例子,
“PK!!}ñU{Š[Content_Types] .xml¢(ÌTÝNº0¾7ñ-Þš‰1†...â€'PÚ3¶ÐμMOÁñöž•Ÿ¨。” 任何帮助都会很棒。

3 个答案:

答案 0 :(得分:6)

手动更改文件名的扩展名实际上并不会更改文件类型。 SaveAs方法采用文件类型参数。你想要的代码是

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

XlFileFormat的Excel帮助中进行搜索,可以(几乎)获得可能的文件格式的完整列表,包括6种文本格式和4种CSV格式。

答案 1 :(得分:2)

在名称中添加txt不会自动将word文档编码为纯文本格式。

改为尝试

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

答案 2 :(得分:0)

ActiveWorkbook.SaveAs方法将双引号添加到文件中每一行的开头和结尾。

此方法解析给定范围内的每一行并将其转换为CSV文件:

Sub SaveSheetToCSVorTXT()
    Dim xFileName As Variant
    Dim rng As Range
    Dim DelimChar As String

    DelimChar = "," 'The delimitation character to be used in the saved file. This will be used to separate cells in the same row

    xFileName = Application.GetSaveAsFilename(ActiveSheet.Name, "CSV File (*.csv), *.csv, Text File (*.txt), *.txt")
    If xFileName = False Then Exit Sub

    If Dir(xFileName) <> "" Then
        If MsgBox("File '" & xFileName & "' already existe.  Overwrite?", vbYesNo + vbExclamation) <> vbYes Then Exit Sub
        Kill xFileName
    End If

    Open xFileName For Output As #1
    'Save range contents. Examples of ranges:
    'Set rng = Activesheet.Range("A1:D4")   'A rectangle between 2 cells
    'Set rng = Activesheet.columns(1)       'An entire column
    Set rng = ActiveSheet.Range("B14").CurrentRegion   'The "region" from a cell. This is the same as pressing CTRL+T on the selected cell

    For i = 1 To rng.Rows.Count
        For j = 1 To rng.Columns.Count
            lineText = IIf(j = 1, "", lineText & DelimChar) & rng.Cells(i, j)
        Next j
        Print #1, lineText
    Next i
    Close #1

    MsgBox "File saved!"
End Sub