【发布时间】:2018-06-24 09:02:38
【问题描述】:
我正在尝试编写一个宏来将 Excel 导出为 CSV,但我对 vba 很陌生。 我现在拥有的是:
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
来自Excel: macro to export worksheet as CSV file without leaving my current Excel sheet
哪个是正确的 csv,但我正试图摆脱多余的“;”在行的末尾。请问有什么办法吗?
例子:
1|2|3|4|5
2|5|3
2| |5
3
出口会给:
1;2;3;4;5
2;5;3;;
2;;5;;
3;;;;
我想要的是:
1;2;3;4;5
2;5;3
2;;5
3
这可能吗?
非常感谢您的帮助
编辑: 这是给出答案后编辑的代码:
Option Explicit
Public Function RemoveTrailing(s As String) As String
Dim nIndex As Integer
For nIndex = Len(s) To 1 Step -1
If Right$(s, 1) = ";" Then
s = Left$(s, Len(s) - 1)
End If
Next
RemoveTrailing = s
End Function
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
'Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
Dim sFile2 As String
Dim sLine As String
sFile2 = Replace(MyFileName, ".csv", "2.csv")
Open MyFileName For Input As #1
Open sFile2 For Output As #2
Do Until EOF(1)
Line Input #1, sLine
Print #2, RemoveTrailing(sLine)
Loop
Close #1
Close #2
End Sub
但我收到错误“类型不兼容”
【问题讨论】: