2017-03-10 2433 views
0

我有一個Excel宏,可以將雅虎的股票代碼信息下載並保存爲csv。然後調用一個函數來處理csv,生成圖表並將生成的xlsm文件存儲爲html文件。VBA將Excel工作表複製到另一個工作簿中的新工作表中

我想將連續的csv文件傳遞到函數中,處理它們並將結果xlsm文件存儲到原始xlsm文件上的新工作表中。

If (Year = 0) Then 
     Application.DisplayAlerts = False 
     ActiveWorkbook.SaveAs Filename:=FilePAth & Ticker & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False 
     ActiveWorkbook.SaveAs Filename:=FilePAth & Ticker & ".htm", FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False 
    Else 
     ActiveWorkbook.Copy After:=Workbooks(FilePAth & Ticker & ".xlsm").Sheets(Ticker) 
     ActiveWorkbook.SaveAs Filename:=FilePAth & Ticker & ".htm", FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False 
     Workbooks(Ticker & ".csv").Close SaveChanges:=True 
    End If 

的上述條件的第一部分創建XLSM & htm文件,第二部分試圖保存在工作表。 發生以下錯誤: - ActiveWorkbook.Copy

任何人都可以提供任何線索嗎?

在此先感謝。

+0

您錯過了一個步驟。嘗試使用'ActiveWorkbook.Copy ...'將其更改爲'ActiveWorkbook.ActiveSheet.Copy ...' – Jeeped

+0

非常感謝您的幫助! – GLW75

回答

0

該代碼查找主工作簿。如果它沒有找到它,那麼它會打開它。隨着開放的主工作簿,工作表可以從另一個移動到另一個。我創造了一種通用的方式來保存和關閉。

這是你需要的行。

ThisWorkbook.Sheets(1).Copy After:=Compiled_WB.Sheets(Compiled_WB.Worksheets.Count) 

這裏是將所有這些一起分。

Sub tryit() 
Application.DisplayAlerts = False 
Dim Ticker As String 
Ticker = "DocumentsTicker" 
Dim year As Long 
year = 1 
Dim Compiled_WB As Workbook 
If (year = 0) Then 
    Application.DisplayAlerts = False 
    ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & Ticker & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False 
    ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & Ticker & ".htm",FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False 
Else 
    For Each Compiled_WB In Workbooks 
     If InStr(Compiled_WB.Name, Ticker) > 0 Then 
     GoTo already_open 
    End If 
    Next 
    Workbooks.Open Filename:=ThisWorkbook.Path & Ticker & ".xlsm" 
    For Each Compiled_WB In Workbooks 
     If InStr(Compiled_WB.Name, Ticker) > 0 Then 
     GoTo already_open 
     End If 
    Next 
already_open: 

    ThisWorkbook.Sheets(1).Copy After:=Compiled_WB.Sheets(Compiled_WB.Worksheets.Count) 

    Dim filetype As String 
    If Compiled_WB.FileFormat = 52 Then 
     filetype = ".htm" 
    Else 
     filetype = ".xlsm" 
    End If 
    Compiled_WB.Save 

    Compiled_WB.SaveAs Filename:=Compiled_WB.Path & "\" & Ticker & filetype, FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False 
    Compiled_WB.Close 

    Workbooks(Ticker & ".csv").Close SaveChanges:=True 
    End If 
    End Sub' 
+0

許多泰克人的幫助! – GLW75

相關問題