我有一个需要转换为CSV的Excel文件。这部分很好,我编写了以下代码:
Private Sub createCSV()
Dim path As String
Dim ws As Excel.Worksheet
path = "\\networkshare\mydir"
For Each ws In Application.ActiveWorkbook.Worksheets
ActiveSheet.Range("1:2").EntireRow.Delete 'Delete the first two rows
ws.SaveAs path & ws.Name, xlCSV
Next
End Sub
但是,
我只需要按特定顺序将特定的列保存到CSV。
excel工作表的A,B列到CSV的D,E列,工作表的C,D列为CSV的A,B列,等等
有没有办法做到这一点?
答案 0 :(得分:0)
请尝试下一个代码(注意路径字符串中的最后一个“”):
Private Sub createCSV()
Dim ws As Worksheet, path As String, arr As Variant, lastRow As Long
path = "\\networkshare\mydir\" 'take care of the last "\"!!!
For Each ws In ActiveWorkbook.Worksheets
ws.Range("1:2").EntireRow.Delete 'Delete the first two rows
lastRow = ws.Range("A" & rows.count).End(xlUp).row 'last row of the sheet
arr = ws.Range("A1:D" & lastRow).Value 'put the range in an array
'switch the array columns
arr = Application.Index(arr, Evaluate("row(1:" & UBound(arr) & ")"), Array(3, 4, 1, 2))
ws.Range("A1").Resize(UBound(arr), UBound(arr, 2)).Value = arr 'drop the adapted array back in the sheet
ws.SaveAs path & ws.Name & ".csv", xlCSV 'save the sheet as csv
Next
End Sub