Excel VBA另存为制表符分隔文件

时间:2016-09-29 09:47:54

标签: excel vba excel-vba

我有一些代码将活动工作表保存为制表符分隔的文本文件,但是其中包含逗号字符的单元格数据会使用引号导出,例如

John Hopkins, Burgers
becomes
"John Hopkins, Burgers"

我该如何解决这个问题?

这是我的代码:

ActiveWorkbook.SaveAs ActiveWorkbook.path & "\" & filename,
FileFormat:=xlText, CreateBackup:=False

添加: 我刚刚发现,如果我再次保存文件,它将删除所有“”。 我可以在代码中添加额外的保存吗?

5 个答案:

答案 0 :(得分:3)

我解决了!由于引号在手动保存为分隔文件时会消失,但在使用

时则不会
ActiveWorkbook.SaveAs ActiveWorkbook.path & "\" & filename,
FileFormat:=xlText, CreateBackup:=False

我刚刚在上面添加了另一个保存,但这次使用sendkey笔划来模仿手动方法。

ActiveWorkbook.SaveAs fil,FileFormat:= _         xlText

SendKeys "^{F4}"
SendKeys "{ENTER}"
SendKeys "{ENTER}"

答案 1 :(得分:1)

根据FileFormat属性,您可以选择以下格式:

xlCSV
xlCSVMac
xlCSVMSDOS
xlCSVWindows

为什么不选择其中一种逗号分隔值格式?

尝试xlCSV

答案 2 :(得分:0)

这是我用来保存普通xlsb文件或xls *文件的一些代码的变体 可以用于许多不同的文件。

Sub SaveAsTDV()

'
' Easy way to export to Tab Deliminated Values
' By DeLaguna
' v17.05.10.15.06
'

Dim BaseFolder As String
    Dim LitProg As String
    Dim Path As String
    Dim Extn As String
      BaseFolder = "YourBase Folder\"    
      FileName = "FileName" 'File name with no Extension.
      Extn = ".txt" 'If choosing somthing other than xlText you may change this.

 Application.DisplayAlerts = False 'Auto Yes to save

    ChDir BaseFolder
        ActiveWorkbook.SaveAs Filename:= BaseFolder & FileName & Extn, _
        FileFormat:=xlText, CreateBackup:=True  'xlText will save as Tab Deliminated text

Application.DisplayAlerts = True ' Reverts to Excel Default showing popup messages for input.

End Sub

希望有人告诉我,如果我犯了任何错误,我必须从中删除敏感信息。

答案 3 :(得分:0)

将FileFormat xlText更改为xlTextPrinter

 ActiveWorkbook.SaveAs ActiveWorkbook.path & "\" & filename,
    FileFormat:=xlTextPrinter, CreateBackup:=False

答案 4 :(得分:0)

我也试图让它工作,发现 WITH properties (id, data) AS ( values (1, '{"ProductType": "ABC","ProductName": "XYZ","attributes": [{"name": "Color","type": "STRING","value": "Silver"},{"name": "Case","type": "STRING","value": "Shells"}]}'::jsonb), (2, '{"ProductType": "ABC","ProductName": "XYZ","attributes": [{"name": "Color","type": "STRING","value": "Red"},{"name": "Case","type": "STRING","value": "Shells"}]}'::jsonb) ) SELECT id, data|| jsonb_build_object( 'attributes', jsonb_agg( case when attribs->>'name' = 'Case' then attribs||'{"value": "Glass"}'::jsonb else attribs end ) ) as data FROM properties m CROSS JOIN LATERAL JSONB_ARRAY_ELEMENTS(data->'attributes') as a(attribs) GROUP BY id, data 不是有效的 xlText,但 FileFormat 是。这可能与版本有关,但以防万一其他人遇到同样的问题。

xlTextWindows

此处保存了 ActiveWorkbook.SaveAs ActiveWorkbook.path & "\" & filename,FileFormat:=xlTextWindows, reateBackup:=False 的有效条目的完整列表

https://docs.microsoft.com/en-us/office/vba/api/excel.xlfileformat