excel - vba pivot does not refresh after adding new lines -
with of vba able create pivot table. when new lines added in sheet , refresh pivot table wkssource1.pivottables(1).refreshtable
, not updating pivot table.
dim pcache pivotcache dim ptable pivottable dim prange range dim lastrowv long dim lastcolv long lastrowv = wkssource.cells(rows.count, 3).end(xlup).row lastcolv = wkssource.cells(5, columns.count).end(xltoleft).column set prange = wkssource.cells(5, 1).resize(lastrowv - 4, lastcolv) activeworkbook.pivotcaches.create(sourcetype:=xldatabase, sourcedata:= _ prange, version:=xlpivottableversion14).createpivottable _ tabledestination:=wkssource1.cells(1, 1), tablename:="pivottable14", _ defaultversion:=xlpivottableversion14 wkssource1.select cells(1, 1).select activesheet.pivottables("pivottable14").pivotfields("term - phases") .orientation = xlrowfield .position = 1 end activesheet.pivottables("pivottable14").pivotfields("status") .orientation = xlcolumnfield .position = 1 end activesheet.pivottables("pivottable14").adddatafield activesheet.pivottables( _ "pivottable14").pivotfields("steps/ activities"), "count of steps/ activities" _ , xlcount
wkssource1.pivottables(1).refreshtable work if pivot cache source data dynamic i.e. if source data excel table data or dynamic named range.
but when creating pivot table, source data range fixed , depends upon range prange.
so when add new data on source data sheet, pivot cache still refers prange not reset somehow.
if refreshing pivot table in sub routine, need update existing pivot cache instead of refreshing pivot table , once pivot cache updated, pivot table updated.
try below code , tweak per need.
sub refreshpivottable() dim wkssource worksheet, wkssource1 worksheet dim prange range dim lastrowv long, lastcolv long set wkssource = sheets("sheet4") 'sheet contains source data pivot table set wkssource1 = sheets("sheet3") 'sheet contains pivot table lastrowv = wkssource.cells(rows.count, 3).end(xlup).row lastcolv = wkssource.cells(5, columns.count).end(xltoleft).column set prange = wkssource.range("c5:f12") wkssource1.pivottables(1).changepivotcache activeworkbook.pivotcaches.create(sourcetype:=xldatabase, sourcedata:=prange) end sub
Comments
Post a Comment