尝试将Range从工作表复制到新工作簿中。 Excel VBA

时间:2015-01-16 19:12:27

标签: excel vba excel-vba export export-to-excel

这就是我所拥有的:

Sub exportDataAM()
Dim wbS As Workbook, wbT As Workbook
Dim wsS As Worksheet, wsT As Worksheet

Set wbS = ThisWorkbook 'workbook that holds this code
Set wsS = wbS.Worksheets("Recap").Range("A1:R5")

wsS.Copy
Set wbT = ActiveWorkbook 'assign reference asap

Set wsT = wbT.Worksheets("Recap").Range("A1:R5")
wsT.Name = "Recap" 'rename sheet

wbT.SaveAs wbS.Path & "\" & "Recap AM" & Format(Now, " dd-mm-yyyy ") 'save new workbook
End Sub

我得到的类型不匹配对我来说对于第6行的.Range没有意义。我知道还有其他方法可以做到这一点,但这没有.Range工作正常我想知道特别是为什么会这样。

对此的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

您已将变量wsSwsT声明为工作表。但是,您尝试在变量中添加范围。这将导致不匹配。

将变量声明为Range,或仅将工作表添加到变量中。

答案 1 :(得分:0)

以下内容应该有效

Private Sub Copy()
Set newBook = Workbooks.Add
With newBook
    .Title = "Recap Am"
    .Subject = "RFQ"
    .SaveAs Filename:="Recap.xls"
  Dim rng As Excel.Range

Set rng = ThisWorkbook.Worksheets("SheetName").Cells.SpecialCells (xlCellTypeVisible)

rng.Copy newBook.Worksheets("Sheet1").Range("A1")

End With
End Sub