从Excel电子表格创建txt文件

时间:2016-07-28 16:20:51

标签: excel vba macros

我使用以下代码从Excel工作表创建.txt文件。但是它似乎在文件的开头产生了另一列,我无法弄清楚原因。任何帮助,将不胜感激。

A9:M287也都填充了内容,因此它不是隐藏的空白列。

Sub StoretoTXT()

Dim answer As Integer

answer = MsgBox("Have all the required fields been filled and are correct?", vbYesNo + vbQuestion, "Data Check")
If answer = vbYes Then
    Dim c As Range, r As Range
    Dim output As String

    For Each r In Range("A9:M287").Rows
        For Each c In r.Cells
            output = output & vbTab & c.Value
        Next c
        output = output & vbNewLine
    Next r

    Open "C:\Test\Desktop" & Format(Now(), "YYYYMMDDHHMMSS") & "Test.txt" For Output As #1
    Print #1, output
    Close

    MsgBox "File has now been created. Excel will now close"
    ActiveWorkbook.Close False
Else
    'do nothing
End If

End Sub

1 个答案:

答案 0 :(得分:0)

使用SaveAs方法创建制表符分隔文件可能更容易。由于您只查找特定范围,因此请先将该范围复制到新工作簿,然后另存为xlText

Sub SaveAsTabDelimited()
Dim rng as Range
Dim newWB as Workbook
Set rng = Range("A9:M287")
Set newWB = Workbooks.Add
Application.DisplayAlerts = False
With newWB
    Do While .Worksheets.Count > 1
        .Worksheets(.Worksheets.Count).Delete
    Loop
End With

rng.Copy newWB.Worksheets(1).Range("A1")
'## Modify path to file output in the next line:
newWB.SaveAs Filename:="C:\Debug\tab-delimited.txt", FileFormat:= _
    xlText, CreateBackup:=False
Application.DisplayAlerts = True
newWB.Close
End Sub