简体   繁体   中英

Trying to copy Range from worksheet into a new workbook. Excel VBA

Here is what I have:

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

I get a Type mismatch which just doesn't make sense to me regarding the .Range on Line 6. I know there are other ways to do this, but this is working fine without the .Range and I wanted to figure out specifically why that may be.

Any help on this will be greatly appreciated.

You have declared the variables wsS and wsT as Worksheets. Yet, you try adding a range into the variable. This will cause a mismatch.

Either declare the variables as Range , or add only the worksheet into the variable.

The following should work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM