我是VBA的新手并尝试从ws复制到wscsv并将后者保存为.csv文件。以下是我的子程序。
我遇到了:
运行时错误1004:应用程序未定义
在这一行:
ActiveWorkbook.SaveAs Filename:=savedirectory, FileFormat:=xlCSV, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
csvworkbook = ActiveWorkbook.Name
我的代码
Sub AddNewWorkbook1(ws As Worksheet)
ws.Activate
MsgBox ("adding new workbook for" & ws.Name)
Dim wscsv As Excel.Workbook
Dim savedirectory As String
Dim currentworkbook As String
Dim csvworkbook As String
currentworkbook = ws.Name
savedirectory = '/Users/Desktop/Magnum/' & currentworkbook
Dim lrow As Long
lrow = Columns("A").End(xlDown).Row
Workbooks.Add
DisplayAlerts = False
ActiveWorkbook.SaveAs (Filename:=savedirectory, FileFormat:=xlCSV, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges)
csvworkbook = ActiveWorkbook.Name
Set wscsv = ActiveWorkbook
MsgBox ("Entering copying")
ws.Range(ws.Cells(2, 1), ws.Cells(lrow, 4)).Copy
wscsv.Sheets(1).Range("A1").PasteSpecial xlPasteValues
ws.Range(ws.Cells(2, "H"), ws.Cells(lrow, "H")).Copy
wscsv.Sheets(1).Range("E1").PasteSpecial xlPasteValues
ws.Range(ws.Cells(2, "E"), ws.Cells(lrow, "E")).Copy
wscsv.Sheets(1).Range("F1").PasteSpecial xlPasteValues
ws.Range(ws.Cells(2, "I"), ws.Cells(lrow, "I")).Copy
wscsv.Sheets(1).Range("G1").PasteSpecial xlPasteValues
lrow = wscsv.Sheets(1).Columns("A").End(xlDown).Row
wscsv.Sheets(1).Range(wscsv.Sheets(1).Cells(2, 1), wscsv.Sheets(1).Cells(lrow, 1)).NumberFormat = "mm/dd/yyyy"
wscsv.Sheets(1).Range("A1").Value = "Date"
wscsv.Sheets(1).Range("B1").Value = "open"
wscsv.Sheets(1).Range("C1").Value = "high"
wscsv.Sheets(1).Range("D1").Value = "low"
wscsv.Sheets(1).Range("E1").Value = "close"
wscsv.Sheets(1).Range("F1").Value = "volume"
wscsv.Sheets(1).Range("G1").Value = "cap"
wscsv.Save
wscsv.Close
MsgBox ("Copying complete")
End Sub
答案 0 :(得分:1)
解决您的错误行,只需使用:
ActiveWorkbook.SaveAs Filename:=savedirectory, FileFormat:=xlCSV, ConflictResolution:=2
(ConflictResolution = 2
,等于xlLocalSessionChanges
,请在此处阅读:https://msdn.microsoft.com/en-us/library/office/ff194803.aspx
但是,您可以通过不使用ws.Activate
,ActiveWorkbook
和csvworkbook = ActiveWorkbook.Name
来改进代码。您可以直接将wscsv
(定义为工作簿)分配给新创建的工作簿。请参阅下面的代码,了解如何引用所有对象。
<强>代码强>
Option Explicit
Sub AddNewWorkbook1(ws As Worksheet)
MsgBox ("adding new workbook for " & ws.Name)
Dim wscsv As Workbook
Dim savedirectory As String
Dim currentworkbook As String
Dim csvworkbook As String
currentworkbook = ws.Name
savedirectory = "Your Path" & "\" & ws.Name
Dim lrow As Long
lrow = ws.Columns("A").End(xlDown).Row
Set wscsv = Workbooks.Add
DisplayAlerts = False
wscsv.SaveAs Filename:=savedirectory, FileFormat:=xlCSV, ConflictResolution:=2
csvworkbook = wscsv.Name
MsgBox ("Entering copying")
' do the rest of your copy >> paste
End Sub
答案 1 :(得分:0)
ActiveWorkbook.SaveAs Filename:=savedirectory, FileFormat:=xlCSV, ConflictResolution:=xlLocalSessionChanges
你能这样试试吗?它对我有用。