2017-06-12 45 views
0

我試圖使用下面的代碼將範圍從啓用宏的工作簿複製到新的Excel文件,然後將其發送到公司。將excel範圍複製到新的xlsx文件

保存新文件爲csv時的代碼工作,但我注意到它丟失了格式,所以我需要將它保存爲excel文件。

我得到一個運行時錯誤1004和消息說方法保存爲對象工作簿失敗。

我所做的唯一更改是將.csv擴展名更改爲.xlsx。

Sub exportJuneCredit() 
    ' 
    ' export Macro 

    Range("A1:H500").Select 
    Selection.Copy 
    Workbooks.Add 
    ActiveSheet.Paste 
    ActiveWorkbook.SaveAs Filename:= _ 
    "file path Credits.xlsx" _ 
    , FileFormat:=xlsx, CreateBackup:=False 
    Application.DisplayAlerts = False 
    ActiveWorkbook.Close 
    Application.DisplayAlerts = True 

End Sub 
+1

它實際上看起來像您還將'FileFormat:= xlCSV'更改爲'FileFormat:= xlsx',這不是可識別的格式。你可能想'FileFormat:= xlOpenXMLWorkbook' – YowE3K

回答

0

試試這個: -

Sub exportJuneCredit() 
    Dim WkSht_Src As Worksheet 
    Dim WkBk_Dest As Workbook 
    Dim WkSht_Dest As Worksheet 
    Dim Rng As Range 

    Set WkSht_Src = ActiveSheet 
     Set Rng = WkSht_Src.Range("A1:H500") 
      Set WkBk_Dest = Application.Workbooks.Add 
       Set WkSht_Dest = WkBk_Dest.Worksheets(1) 
        Rng.Copy WkSht_Dest.Range("A1") 
       Set WkSht_Dest = Nothing 
       WkBk_Dest.SaveAs Filename:="file path Credits.xlsx", FileFormat:=XlFileFormat.xlWorkbookNormal, CreateBackup:=False 
       WkBk_Dest.Close 0 
      Set WkBk_Dest = Nothing 
     Set Rng = Nothing 
    Set WkSht_Src = Nothing 

End Sub 

的問題,我相信你有是activeworkbook可能不是你想要的工作簿保存,來解決這個問題我已經明確宣佈項目。

我還更改了複製/粘貼以使用複製功能。

+0

完美。謝謝 – PA060

+1

儘管在創建後不會讓我打開文件。如YowE3K所述,將文件格式更改爲:xlOpenXMLWorkbook。 – PA060

相關問題