在VBA中获取最后一个单元的问题

时间:2016-08-05 03:00:04

标签: excel vba excel-vba

我正在尝试编写代码来创建数据透视表(作为更大代码的一部分),而我却无法检测源数据。不幸的是,每次代码运行时,数据都会有不同的行数,所以我希望代码能够自动找到包含数据的最后一个单元格。 我一直收到错误声明需要一个对象或者没有定义一个变量。尽管去了VBA错误指南,但我无法找到问题所在。

谁能看到这里的问题是什么?或者即使有更有效的方法可以做到这一点?

Sub CreatePivotTable()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As Range, LRow As Range, LCol As Range

'Determine the data range you want to pivot
 Set LRow = Cells(Rows.Count, 1).End(xlUp).Row
 Set LCol = Cells(1, Columns.Count).End(xlToLeft).Column
 Set SrcData = Worksheets("Raw Data").Range("A1:Cells(LRow,LCol)")

'Create a new worksheet
    Sheets.Add.Name = "Pivot Table"
'Where do you want Pivot Table to start?
    StartPvt = Worksheets("Occupancy").Range("A15")

'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase,  SourceData:=SrcData)

'Create Pivot table from Pivot Cache
    Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, TableName:="Occupancy")

'Create the headings and row and column orientation
    pvt.PivotFields("Precinct").Orientation = xlPageField
    pvt.PivotFields("Number").Orientation.xlDataField.Function = xlCount
    pvt.PivotFields("Captured Date").Orientation.xlColumnField.Position = 1
    pvt.PivotFields("Captured Session").Orientation.xlColumnField.Position = 2
    pvt.PivotFields("Session Location").Orientation.xlRowField.Position = 1

'Turn on Automatic updates/calculations --like screenupdating to speed up code
    pvt.ManualUpdate = False

End Sub

2 个答案:

答案 0 :(得分:4)

引号内的任何内容都是一个字符串,因此"A1:Cells(LRow,LCol)"成为一个字符串,并且不会获取单元格的地址(LRow,LCol)

更改

Set SrcData = Worksheets("Raw Data").Range("A1:Cells(LRow,LCol)")

LastCol = Split(Cells(, LCol).Address, "$")(1)
Set SrcData = Worksheets("Raw Data").Range("A1:" & LastCol & LRow)

或者

Set SrcData = Worksheets("Raw Data").Range("A1:" & Cells(LRow,LCol).Address(False, False))

同时更改

Dim LRow As Range, LCol As Range

Set LRow = Cells(Rows.Count, 1).End(xlUp).Row
Set LCol = Cells(1, Columns.Count).End(xlToLeft).Column

Dim LRow As Long, LCol As Long

LRow = Cells(Rows.Count, 1).End(xlUp).Row
LCol = Cells(1, Columns.Count).End(xlToLeft).Column

答案 1 :(得分:0)

使用表来存储数据并为其命名。然后将数据透视表源设置为表名