2011-04-05 290 views
0

我记录了为任意数据创建数据透视表,并且在给定一组数据时它似乎工作正常。但是,当程序获得多列数据时,输出不正确。下面是一般透视表的代码。它与记录的数据透视表类似,不同之处在于名称和列的硬编码较少VBA Excel数据透视表

Dim tempString As String 

    tempString = ActiveWorkbook.Sheets(sheetName).Range(column & "1").Value 

    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
     sheetName & "!R1C" & ColTextToInt(column) & ":R" & g_totalRow & "C" &  ColTextToInt(column) & "", Version:=xlPivotTableVersion12 _ 
     ).CreatePivotTable TableDestination:=ActiveSheet.Range(colNamePos & "1"), _ 
     TableName:=column & "Table", DefaultVersion:=xlPivotTableVersion12 
    ActiveCell(1, ColTextToInt(colNamePos)).Select 
    With ActiveSheet.PivotTables(column & "Table").PivotFields(tempString) 
     .Orientation = xlRowField 
     .Position = 1 
    End With 
    ActiveSheet.Range(colNamePos & "1").Select 
    ActiveWorkbook.ShowPivotTableFieldList = True 
    ActiveSheet.PivotTables(column & "Table").AddDataField ActiveSheet.PivotTables(_ 
     column & "Table").PivotFields(tempString), "Count of " & tempString, xlCount 
    ActiveWorkbook.ShowPivotTableFieldList = False 

该程序向上结束。下面是具体的线路:

ActiveSheet.PivotTables(column & "Table").AddDataField ActiveSheet.PivotTables(_ 
     column & "Table").PivotFields(tempString), "Count of " & tempString, xlCount 

在这行代码被击中的数据透视表的列(具有特定的单元名称)被覆盖了一共有多少行有盛大总数。下面是变量所代表的关键点

sheetName =包含所有原始数据的工作表(例如“Sheet1”) column = User指定他们希望程序查看的列(例如“F” ) tempString =给定前两个变量,这将等于列的标题(例如“State”) g_totalRow =原始数据表中有多少行 colNamePos =程序将输入数据透视表的列到

谢谢

杰西Smothermon

回答

1

明白了。导致错误的代码位需要位于“with”部分的前面。我不完全确定这是为什么,但我尝试了它,它的工作。如果有人认为他们有理由说明为什么它需要在我想知道的与之前。

代码:

tempString = ActiveWorkbook.Sheets(sheetName).Range(column & "1").Value 

    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
     sheetName & "!R1C" & ColTextToInt(column) & ":R" & g_totalRow & "C" & ColTextToInt(column) & "", Version:=xlPivotTableVersion12 _ 
     ).CreatePivotTable TableDestination:=ActiveSheet.Range(colNamePos & "1"), _ 
     TableName:=column & "Table", DefaultVersion:=xlPivotTableVersion12 
    ActiveCell(1, ColTextToInt(colNamePos)).Select 
    ActiveSheet.PivotTables(column & "Table").AddDataField ActiveSheet.PivotTables(_ 
     column & "Table").PivotFields(tempString), "Count of " & tempString, xlCount 
    With ActiveSheet.PivotTables(column & "Table").PivotFields(tempString) 
     .Orientation = xlRowField 
     .Position = 1 
    End With 
    ActiveWorkbook.ShowPivotTableFieldList = False 

谢谢

杰西Smothermon