我需要将excel表格中的数据导出到csv中。我所拥有的代码就是这么做的。但是我的Excel数据中的一些列中包含公式。因此,当导出到“csv”时,我得到“0”而不是值。
是否有对csv的专属支持?或者将单元格值导出到csv的任何其他方法。
我目前的代码是:
Sub submit_task()
'
' submit_task Macro
'
'
Dim Filename As String
Dim WB As Workbook
Application.DisplayAlerts = False
Filename = "Job_Details.csv"
'Copy the contents of required sheet ready to paste into the new CSV
Sheets("output_sheet").Range("A3:C4").Copy 'Define your own range
'Open a new XLS workbook, save it as the file name
Set WB = Workbooks.Add
With WB
.Title = "Job Details"
.Subject = "Task Submitted"
.Sheets(1).Select
ActiveSheet.Paste
.SaveAs "C:\UI\" & Filename, xlCSV
.Close
End With
Application.DisplayAlerts = True
End Sub
答案 0 :(得分:1)
尝试使用PasteSpecial
方法。
请参阅MSDN上的资源: https://msdn.microsoft.com/en-us/library/office/ff839476.aspx
另见: Excel VBA Copy Paste Values only( xlPasteValues )
您可能想尝试:
ActiveSheet.PasteSpecial xlPasteValues
像这样:
'Open a new XLS workbook, save it as the file name
Set WB = Workbooks.Add
With WB
.Title = "Job Details"
.Subject = "Task Submitted"
.Sheets(1).PasteSpecial xlPasteValues
.SaveAs "C:\UI\" & Filename, xlCSV
.Close
End With
答案 1 :(得分:0)
我测试过这个并没有产生错误。我认为你可能遇到的问题是excel如何处理与从头开始创建的新工作簿的交互,然后粘贴到那个。在这种情况下,我刚刚创建了一个新工作表,将数据复制到该新工作表,然后将工作表移动到自己的工作簿实例中。然后,新实例将保存在所需的CSV中并关闭。
Sub Create_CSV()
Application.DisplayAlerts = False
'Select & copy data for CSV
Range("A3:C4").Select
Selection.Copy
'Add a new sheet to become your csv and paste data
Sheets.Add After:=ActiveSheet
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
'Move the sheet into it's own instance
ActiveSheet.Move
'Rename the tab
ActiveSheet.Name = "Task Submitted"
'Save the WB as a CSV and close
ActiveWorkbook.SaveAs Filename:="C:\UI\Job_Details.csv", FileFormat:= _
xlCSVMSDOS, CreateBackup:=False
ThisWorkbook.Saved = True
ActiveWindow.Close
Application.DisplayAlerts = True
End Sub