2015-02-24 88 views
0

我想創建一個數據透視表。使用記錄宏函數我創建了一個小的數據透視表,但是當我嘗試從記錄的宏中調整代碼時,我得到一個錯誤(類型不匹配)。Excel使用從記錄的宏PivotCaches.Create

錄製的宏如下所示:

Sheets.Add 
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
     "tadasEquities_20150223133033!R1C1:R780C71", Version:=xlPivotTableVersion14). _ 
     CreatePivotTable TableDestination:="Sheet52!R3C1", TableName:= _ 
     "PivotTable32", DefaultVersion:=xlPivotTableVersion14 
    Sheets("Sheet52").Select 
    Cells(3, 1).Select 
    With ActiveSheet.PivotTables("PivotTable32").PivotFields("Research type") 
     .Orientation = xlRowField 
     .Position = 1 
    End With 

這是我調整了代碼的一部分。

 Worksheets("Pivot Table").PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
     rngData, Version:=xlPivotTableVersion14). _ 
     CreatePivotTable TableDestination:=Worksheets("Pivot Table").Cells(1, 1), TableName:= _ 
     "PivotTable", DefaultVersion:=xlPivotTableVersion14 

rngData定義爲:

Set wsData = Worksheets(1) 
Set rngData = wsData.Range(Worksheets(1).Cells(1, 1), Worksheets(1).Cells(downlast, rightlast)) 

工作表( 「透視表」)是

Worksheets.Add(After:=Worksheets(1)).Name = "Pivot Table" 

其中rightlast和downlast是一個表的最後的細胞。

正如你所看到的,我只調整SourceData和TableDestination,並使用工作表而不是ActiveWorkbook。有人能告訴我我做錯了什麼嗎?

回答

0

對於SourceData和TableDestination,我使用了以下兩行。數據透視表現在運行良好。

dataSource = Worksheets(1).Name & "!" & Worksheets(1).Range(Cells(1, 1), Cells(downlast, rightlast)).Address(ReferenceStyle:=xlR1C1) 'Set the source data, you can make this dynamic if you want 
destination = Worksheets(2).Name & "!" & Worksheets(2).Range("A1").Address(ReferenceStyle:=xlR1C1) 
0

您需要通過SourceDataTableDestinationString這樣的:

Worksheets("Pivot Table").PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
    rngdata.Address(, , xlR1C1, True), Version:=xlPivotTableVersion14). _ 
    CreatePivotTable TableDestination:=Worksheets("Pivot Table").Cells(1, 1) _ 
    .Address(, , xlR1C1, True), TableName:="PivotTable", _ 
    DefaultVersion:=xlPivotTableVersion14 

你做什麼,你是在兩個參數傳遞Range Object
我們簡單地使用Range Object Address Property(它返回一個字符串),其參考風格設置爲R1C1,外部設置爲True以將工作表名稱包含在地址中。
這編譯但未經測試。 HTH。

+0

感謝您的回答。但是,我仍然收到錯誤:對象不支持此屬性或方法。另外,[msdn.microsoft](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.pivotcaches.create%28v=office.14%29.aspx)表示, SourceData可以是Range對象:如果SourceType不是xlExternal,則SourceData參數是必需的。它可以是Range對象(當SourceType是xlConsolidation或xlDatabase時)或Excel WorkbookConnection對象(當SourceType是xlExternal時)。 – tadalendas 2015-02-24 10:44:55

+0

@Tadas我剛剛查看了你發佈的代碼的工作原理。在那段代碼中,你在參數上傳遞了'String'。這是你嘗試過的唯一區別(其中你傳遞了對象)。 – L42 2015-02-25 00:48:19