AME
AME

Reputation: 5300

Type Mismatch 13 Error - Referencing an object

I created a subroutine to store all the cells in a worksheet in an object called "CNrng3".

Sub GetCLRange()
Dim CLrng1 As Range
Dim CLrng2 As Range
Sheets("Cancel").Activate
Set CLrng1 = Cells.Find("*", [a1], , , xlByRows, xlPrevious)
Set CLrng2 = Cells.Find("*", [a1], , , xlByColumns, xlPrevious)
If Not CLrng1 Is Nothing Then
    Set CLrng3 = Range([a1], Cells(CLrng1.Row, CLrng2.Column))
Application.Goto CLrng3
Else
    MsgBox "sheet is blank", vbCritical
End If
End Sub

Now, I want to reference this object to create a pivot with the data:

ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    CLrng3.Cells, Version:=xlPivotTableVersion12).CreatePivotTable _
    TableDestination:="CancelSummary!R1C1", TableName:="CancelPivot", _
    DefaultVersion:=xlPivotTableVersion12

The issue is that I'm getting "Type Mismatch Error 13" when I run this part of the code. Does anyone have an idea why I may be receiving this error and how to fix it?

Thanks!

Upvotes: 1

Views: 655

Answers (1)

brettdj
brettdj

Reputation: 55702

If you try recording the code with the macro recorder you will see that the SourceRange expects to see an address such as "Cancel!R1C1:R10C5" which includes the sheet name

So rather than

SourceData:= CLrng3.Cells

try

SourceData:=(Clrng3.Parent.Name & "!" & Clrng3.Address)

which returns in three parts

  1. "Cancel" (as the name of the parent of your range)
  2. "!"
  3. and something like A1:E10

giving Cancel!A1:E10

 Sub GetCLRange()
    Dim CLrng1 As Range
    Dim CLrng2 As Range
    Dim Clrng3 As Range
    Sheets("Cancel").Activate
    Set CLrng1 = Cells.Find("*", [a1], , , xlByRows, xlPrevious)
    Set CLrng2 = Cells.Find("*", [a1], , , xlByColumns, xlPrevious)
    If Not CLrng1 Is Nothing Then
        Set Clrng3 = Range([a1], Cells(CLrng1.Row, CLrng2.Column))
        ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
                                          ("'" & Clrng3.Parent.Name & "'!" & Clrng3.Address), Version:=xlPivotTableVersion12).CreatePivotTable _
                                          TableDestination:="CancelSummary!R1C1", TableName:="CancelPivot", _
                                          DefaultVersion:=xlPivotTableVersion12
        Application.Goto Clrng3
    Else
        MsgBox "sheet is blank", vbCritical
    End If
End Sub

Upvotes: 6

Related Questions