[英]How to create a manipulated CSV file from XLS using VBA
I have an excel file that I need to convert into a CSV.我有一个需要转换为 CSV 的 excel 文件。 This part is fine, I wrote this code to do so:
这部分很好,我写了这段代码来做到这一点:
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
However,然而,
I need to only save specific columns to CSV in a certain order.我只需要按特定顺序将特定列保存到 CSV。
Column A,B of excel worksheet to Column D,E of CSV and Column C,D of worksheet as column A,B of CSV,etc excel工作表的A、B列到CSV的D、E列和工作表的C、D列作为CSV的A、B列等
Is there a way to do this?有没有办法做到这一点?
Try the next code, please (take care of the last "" in path string):请尝试下一个代码(注意路径字符串中的最后一个“”):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.