2017-07-11 88 views
1

我試圖在Excel 2010 VBA中另存爲。 Excel文件有8張,我認爲這就是爲什麼我無法輕鬆保存爲單元格值的原因。它就像代碼找不到「K2」(請參閱​​下面的代碼失敗的註釋)。運行時錯誤1004在Excel Book中使用多個表單另存單元格值

Sub RecFilter() 
ActiveSheet.Range("$A$2:$H$159").AutoFilter Field:=7, Criteria1:=Array(_ 
    "(1)", "(112)", "(113)", "(126)", "(14)", "(144)", "(216)", "(3,274)", "(448)", "(468)", _ 
    "(5)", "(65)", "(72)", "(80)", "(900)", "(960)", "106", "14", "2", "2,880", "3,420", "504" _ 
    , "513", "56", "665", "72", "845", "9,814", "900"), Operator:=xlFilterValues 
Cells.Select 
Selection.Copy 
Sheets.Add After:=Sheets(Sheets.Count) 
ActiveSheet.Paste 
ActiveSheet.Columns("A:H").EntireColumn.AutoFit 
ActiveSheet.Rows("1:2").Select 
Application.CutCopyMode = False 
Selection.Delete Shift:=xlUp 
ActiveSheet.Range("J1").Select 
ActiveCell.FormulaR1C1 = "Start Date" 
ActiveSheet.Range("J2").Select 
ActiveCell.FormulaR1C1 = "End Date" 
ActiveSheet.Range("K1").Select 
ActiveCell.FormulaR1C1 = "1/1/2000" 
ActiveSheet.Range("K2").Select 
ActiveCell.FormulaR1C1 = "1/7/2000" 
ActiveSheet.Columns("K:K").Select 
Selection.NumberFormat = "m/d/yyyy" 

Application.DisplayAlerts = False 
Dim Path As String 
Dim filename As String 
Path = "C:\Users\TEST\Desktop\" 

'THIS IS WHERE IS FAILS 
filename = ActiveSheet.Range("K2") 

ActiveWorkbook.SaveAs filename:=Path & filename & ".xlsx", 
FileFormat:=xlOpenXMLWorkbook 
End Sub 

回答

1

您正在試圖通過filename = ActiveSheet.Range("K2").ValueActiveWorkbook.SaveAs filename:其中Range("K2").Value包含正斜槓不能包含在保存的文件名字符。 ActiveSheet.Range("K2").Select ActiveCell.FormulaR1C1 = "1/7/2000"

C:\Users\TEST\Desktop\1/7/2000.xlsx不是一個有效的文件名。

嘗試將Range("K2").Value更改爲帶連字符的日期數據類型。

0

更改爲:

filename = ActiveSheet.Cells(2, 11).Value 
+0

運行時錯誤1004 –

+0

現在編輯。單元格(2,11)與K2相同 –

1

K2包含對文件名無效的字符。 嘗試用別的東西代替\符號。例如下劃線(_)。

您可以在K2中自行替換它,但這會打破它作爲日期的用處。

更好的選擇是僅替換文件名。

使用此行:

Filename = Replace(ActiveSheet.Range("K2"), "/", "_") 
相關問題