我有一个存在于空工作簿中的宏。 每天都会粘贴数据,然后运行宏。 宏的一部分是它更新数据透视表中的数据源并刷新。当我粘贴数据并运行宏时,它会抛出一个空白列标题的错误消息。动态元素似乎没有正常工作。
Thing.objects.annotate(
favorited=Count(Case(
When(
favorites__user=john_cleese,
then=1
),
default=0,
output_field=BooleanField(),
)),
)
答案 0 :(得分:2)
我之前从未使用过.SpecialCells(xlLastCell)
,所以我不确定它有多可靠。当您粘贴新数据时,它仍然可以考虑旧列,因为存在一些格式。如果删除旧数据时,只需使用删除键而不是物理删除单元格,就会发生这种情况。以下是我建议如何获得新范围:
Sub PivotTable()
Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim lrow_data As Long
Dim lcol_data As Long
Dim DataRange As Range
Dim PivotName As String
'Set Variables Equal to Data Sheet and Pivot Sheet
Set Data_sht = ThisWorkbook.Worksheets("Sheet1")
Set Pivot_sht = ThisWorkbook.Worksheets("Pivot Table")
'Enter in Pivot Table Name
PivotName = "PivotTable"
'Dynamically Retrieve Range Address of Data
With Data_sht
lrow_data = .Cells(Cells.Rows.Count, 1).End(xlUp).Row 'gets last row
lcol_data = .Cells(1, Cells.Columns.Count).End(xlToLeft).Column 'gets last column
Set DataRange = .Range(.Cells(1, 1), .Cells(lrow_data, lcol_data))
End With
'Make sure every column in data set has a heading and is not blank (error prevention)
If WorksheetFunction.CountBlank(DataRange.Rows(1)) > 0 Then
MsgBox "One of your data columns has a blank heading." & vbNewLine _
& "Please fix and re-run!.", vbCritical, "Column Heading Missing!"
End
End If
'Change Pivot Table Data Source Range Address
Pivot_sht.PivotTables(PivotName).ChangePivotCache _
ThisWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=DataRange)
'Ensure Pivot Table is Refreshed
Pivot_sht.PivotTables(PivotName).RefreshTable
End Sub
注意:此答案假定您的数据始终从A1开始粘贴,并且数据集中每一行的A列都会有值。