更正Excel宏以将复制Excel文件另存为TXT或CSV

时间:2015-08-30 12:34:19

标签: excel vba excel-vba

所以我有这个自制的 Excel宏模板。

enter image description here

我在xlsm文件中插入的宏代码的任务是将副本保存在具有不同格式的同一文件夹中。该格式为.txt(见下图)

enter image description here

宏的预期结果(保存后)应该与excel文件相同(可视化),但这次是.txt格式。

不幸的是,那并没有发生。它生成一个不同的txt文件,它包含不可读的字母数字字符,这是生成的txt文件的一个示例。

    ¬TËNÃ0 ¼#ñ ‘¯(vဠjÚ  #   °µ· ©c[^SÚ¿g“–
P  ö '±wfvìq 8o\1ÃD6øJœËž(Ðë`¬ŸTâõå¾¼  eð \ðX‰ ’  NOú/‹ˆTpµ§JÔ9Çk¥H×Ø É ÑóÌ8¤ 2 ¦‰Š §0AuÑë]* |FŸËÜbˆAÿ Çðîrq7çßK%#ëEq³\×RU btVCf¡jæ l¨ã±Õ(g#xJá
u j#XBG{Ð~J.Wr%WvŒTÛHgÜÓ †vf»ÜUÝ#ûœ¬Áâ  R~€†›Rs§>BšŽB˜ÊÝ «žq®ÑIª ³l@§pçaä ý ë¿ î`ê*IuÃù (  ³´Ü ýÞð JŠ   Át` “m'Ýû  ™    ªîy¸„ f !å…C:r·KÐ}Ì5$4Ï9q Ž.à;ö. ¼]  H ¼„ÿwá+mu   S¶¸ŽÃ¦Ã¶fäÔ l;¶×‚A³ [u×Ðà   ÿÿ  PK          ! µU0#ô   L       _rels/.rels ¢  (                                       

这是我的宏代码:

Sub SaveMe()
    Dim FName As Range
    Dim firstDate As String
    Dim firstTime As String
    Dim answer As Integer

    firstDate = Format(Date, "mmddyyyy")
    firstTime = Format(Now, "hhmmssAM/PM")

    Set FName = Range("H5")
    ActiveWorkbook.SaveCopyAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".txt", FileFormat:=xlText, CreateBackup:=False

End Sub

我想知道是否有人可以查看我的代码并帮助指出什么是错误的。

2 个答案:

答案 0 :(得分:1)

看起来你想要SaveAs而不是SaveCopyAs。

Fileformat xlText或xlTextMSDOS

您可以两步完成此过程。保存副本,然后将其打开,并将其另存为文本文件。

ActiveWorkbook.SaveCopyAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".xlsx"

Workbooks.Open (ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".xlsx")

ActiveWorkbook.SaveAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".txt", FileFormat:=xlText, CreateBackup:=False

https://msdn.microsoft.com/en-us/library/office/ff841185.aspx

https://msdn.microsoft.com/en-us/library/office/ff198017.aspx

答案 1 :(得分:0)

从我的帖子看到这里。 Excel VBA Export To Text File with Fixed Column Width + Specified Row and Columns Only + Transpose

循环所有行和所有单元格。将每个值发送到padspace函数。为每个单元格值构建字符串,并在单元格值之后填充空格。

您必须添加对工作簿的引用。在VBA IDE中,转到工具下拉菜单并选择引用。然后向下滚动并选择“Microsoft Scripting Runtime”。然后点击OK。

将填充空间函数调用参数调整为适合电子表格中数据的数字。因此,您将使用padspace调用更改行中的20。 PadSpace(20,len(cellValue))

这将执行所有行和列。

Public Sub MyMacro()

Dim lRow As Long
Dim lCol As Long
Dim strRow As String
Dim ws As Excel.Worksheet
Dim ts As TextStream
Dim fs As FileSystemObject

'Create the text file to write to
Set fs = New FileSystemObject
Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False)

Set ws = Application.ActiveSheet

'Loop through all the rows.
lRow = 1
Do While lRow <= ws.UsedRange.Rows.count

    'Clear the string we are building
    strRow = ""

    'Loop through all the columns for the current row.
    lCol = 1
    Do While lCol <= ws.UsedRange.Columns.count
        'Build a string to write out. 
        strRow = strRow & ws.Cells(lRow, lCol) & PadSpace(20, Len(ws.Cells(lRow, lCol)))
        lCol = lCol + 1
    Loop

    'Write the line to the text file
    ts.WriteLine strRow

    lRow = lRow + 1
    ws.Range("A" & lRow).Activate
Loop

ts.Close: Set ts = Nothing
Set fs = Nothing

End Sub

'This function will take the max number of spaces you want and the length of the string in the cell and return you the string of spaces to pad.
Public Function PadSpace(nMaxSpace As Integer, nNumSpace As Integer) As String
    If nMaxSpace < nNumSpace Then
        PadSpace = ""
    Else
        PadSpace = Space(nMaxSpace - nNumSpace)
    End If
End Function