2016-08-02 51 views
-1

我需要從我的excel表格導出數據到csv。我有這樣的代碼。但我的Excel數據中的一些列中有公式。所以,出口到「csv」時,我得到的是「0」而不是價值。使用pastespecial將excel數據複製到csv中

是否有對csv的pastespecial支持?!或者以任何其他方式將單元格值導出爲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

嘗試用'ActiveSheet.Range( 「A1」)。PasteSpecial的xlPasteValues' – Slai

回答

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 
+0

更換'ActiveSheet.Paste'我試過了。對於pasteSpecial,我得到一個錯誤,「PasteSpecial方法的工作表類失敗」。 – SanjChau

+0

@SanjChau我已經添加了更多示例代碼供您試用 – GisMofx

+0

仍然是相同的錯誤:( – SanjChau

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 
相關問題