如何使用VBA将多个excel列导出到文本文件而不使用制表符缩进?

时间:2017-07-05 05:59:37

标签: excel vba excel-vba

我试图将两列导出到文本文件中。我写了以下代码:

Dim wb As Workbook
Dim WorkRng As Range
Dim saveFile As String
//Some code for selecting the range

Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).Paste

//Code for saving the file in *.txt
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False

保存文件后。两列中的行被粘贴为Tab分隔。有没有什么方法可以粘贴它们而不进行任何缩进?

如其中一个答案中所述,如果文件格式为xlCSV,我将获得一个包含逗号分隔值的文件。同样,我想知道如何获得":"个分隔列。

1 个答案:

答案 0 :(得分:1)

在保存之前,您可以遍历每一行并连接两列。

Dim wb As Workbook
Dim WorkRng As Range
Dim saveFile As String
Dim sh As Worksheet
Dim rw As Range

//Some code for selecting the range

Set wb = Application.Workbooks.Add
WorkRng.Copy

Set sh = wb.Worksheets(1)
sh.Paste

For Each rw In sh.Rows
  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  rw.Cells(rw.Row, 1).Value = Concat(rw.Cells(rw.Row, 1).Value, rw.Cells(rw.Row, 2).Value)
  rw.Cells(rw.Row, 2).Value = ""
Next rw

//Code for saving the file in *.txt
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False