如何使用excel vba将excel文件转换为CSV文件(pipe道分隔符)

我想将简单的Excel文件转换为CSV(pipe道分隔)使用Excel VBA我试图很多代码,但不能得到预期的输出

following code I tried Sub mergeFiles() Dim xlwkbInput1 As Workbook Dim xlshtInput1 As Worksheet Dim xlwbfinalrpt As Workbook Dim xlshtfinalrpt As Worksheet Dim rcount1 As Long Dim xlwkbInput2 As Workbook Dim xlshtInput2 As Worksheet Dim xlapp As Excel.Application Set xlapp = New Excel.Application xlapp.Visible = True Set xlwkbInput1 = xlapp.Workbooks.Open(ActiveWorkbook.Path & "\Output\Operative_CashFlow_Report.xlsx") Set xlwkbInput2 = xlapp.Workbooks.Open(ActiveWorkbook.Path & "\Output\Collection_CashFlow_Report.xlsx") xlwkbInput2.Sheets("Sheet1").Activate xlwkbInput2.ActiveSheet.UsedRange.Copy xlwkbInput1.Sheets("Sheet1").Activate rcount = xlwkbInput1.ActiveSheet.UsedRange.Rows.Count xlwkbInput1.Sheets("Sheet1").Range("A" & CStr(rcount + 1)).PasteSpecial xlwkbInput1.UsedRange("$A$1:$I$274").AutoFilter Field:=1, Criteria1:=Array( _ "LIC106", "LIC107", "LIC134", "LIC138", "="), Operator:=xlFilterValues xlwkbInput1.UsedRange.Delete xlwkbInput1.SaveAs ActiveWorkbook.Path & "\Output\final_report.xlsx" Set xlwbfinalrpt = xlapp.Workbooks.Open(ActiveWorkbook.Path & "\Output\final_report.xlsx") xlwbfinalrpt.Sheet("Sheet1").Activate xlwbfinalrpt.SaveAs ActiveWorkbook.Path & "\Output\final_report.xlsx" xlwbfinalrptwb = Workbooks.Open (ActiveWorkbook.Path & "\Output\final_report.xlsx" xlwbfinalrptwb .SaveAs fileName:=ActiveWorkbook.Path & "\Output\final_report.xlsx" , FileFormat:=xlCSV, CreateBackup:=False 

'在这里我在做excel转换为CSV文件

 End Sub 

您可以将Excel文件保存为逗号分隔符或制表符分隔符,但不能使用pipe道分隔符。

以下是如何实现pipe道分隔的导出。

基本样本

只是为了展示基本面。

 Sub Writing_to_a_text_file() Dim N As Integer Dim FileName As String 'Define where to save the output file. FileName = Environ("USERPROFILE") & "\Desktop\" & "Sample1.csv" 'Get a free file number N = FreeFile Open FileName For Output As #N '"Print" print data into the file. Another method is "Write". 'Both do the same job but behave slightly differently. Try Google it. Print #N, "This is a test" Print #N, "Writing another line here" Print #N, Join(Array("Pipe", "delimited", "line", "here"), "|") Print #N, vbNullString '<- this create an empty line Close N End Sub 

以pipe道分隔格式将一系列数据导出到文本文件中

 Sub ExportToTextFile() 'Export range("A1:E10") data to a text file in pipe delimited format. Dim N As Integer Dim FileName As String Dim R As Long, C As Long, DataLine As String FileName = Environ("USERPROFILE") & "\Desktop\" & "TextOutput.csv" N = FreeFile Open FileName For Output As #N For R = 1 To 10 DataLine = vbNullString For C = 1 To 5 DataLine = DataLine & "|" & Cells(R, C).Value2 Next C DataLine = Right(DataLine, Len(DataLine) - 1) Print #N, DataLine Next R Close N End Sub