使用多个表格从Excel工作簿中的一个工作表中保存单元格值

时间:2017-07-11 14:52:49

标签: excel vba excel-vba excel-2010

我正在尝试在Excel 2010 VBA中保存。 Excel文件有8张,我认为这就是为什么我不能轻易保存为单元格值的原因。这就像代码找不到" K2" (请参阅下面的代码失败的注释)。运行时错误1004.

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

3 个答案:

答案 0 :(得分:1)

您正尝试将filename = ActiveSheet.Range("K2").Value传递给ActiveWorkbook.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不是有效的文件名。

尝试将{{1}}更改为带连字符的日期数据类型。

答案 1 :(得分:1)

K2包含对文件名无效的字符。 尝试用其他东西替换\符号。例如下划线(_)。

您可以在K2中替换它,但这会破坏它作为日期的用处。

更好的选择是仅替换文件名。

使用此行:

Filename = Replace(ActiveSheet.Range("K2"), "/", "_")

答案 2 :(得分:0)

更改为:

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