首先,如果这个问题太明显,我提前道歉。我只是几年没有使用 VBA 和 Excel,而且在其他地方找不到我的问题的答案。
我希望我的 VBA 程序从工作表“ReportData”中获取数据,并使用它在新工作表“Report”上创建一些数据透视表。
我的问题是关于单元格引用的。我认为,只要激活或选择一个工作表,那么该工作表就成为 VBA 的参考点。因此,像 Cells(1,1).Value 这样的语句将查看活动工作表的第一个单元格中的值。但是,我不知道为什么它对我不起作用。
这是适合我的版本:
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim ReportSheet As Worksheet
Dim ItemName As String
Dim Row As Long, Col As Long, i As Long
Application.ScreenUpdating = False
'Delete Report sheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Report").Delete
On Error GoTo 0
'Add Report sheet
Set ReportSheet = Worksheets.Add
ActiveSheet.Name = "Report"
'Create Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=Sheets("ReportData").Range("A1").CurrentRegion)
Row = 1
For i = 1 To 4
For Col = 1 To 7
ItemName = Sheets("ReportData").Cells(1, i + 2)
With Sheets("Report").Cells(Row, Col)
.Value = ItemName
.Font.Size = 16
End With
.
.
.
.
Next Col
Next i
我的问题是关于以下行:
With Sheets("Report").Cells(Row, Col)
为什么我需要添加
“表格(“报告”)。”
?我以为最后激活的工作表是“报告”。因此,如果我使用:
带单元格(行、列)
单独 - 不应该自动引用
工作表(“报告”).单元格(行,列)
? (事实并非如此)。
我还尝试在引用单元格之前激活“报告”工作表,但这也不起作用。例如,以下内容对我不起作用。它继续引用“ReportData”工作表中的单元格(这不是我想要引用的工作表):
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim ReportSheet As Worksheet
Dim ItemName As String
Dim Row As Long, Col As Long, i As Long
Application.ScreenUpdating = False
'Delete Report sheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Report").Delete
On Error GoTo 0
'Add Report sheet
Set ReportSheet = Worksheets.Add
ActiveSheet.Name = "Report"
'Create Pivot Cache
Set PTCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=Sheets("ReportData").Range("A1").CurrentRegion)
Row = 1
For i = 1 To 4
For Col = 1 To 7
ItemName = Sheets("ReportData").Cells(1, i + 2)
Worksheets("Report").Activate
With Cells(Row, Col)
.Value = ItemName
.Font.Size = 16
End With
.
.
.
.
Next Col
Next i
第二个例子不起作用是什么?这让我发疯。我认为您所要做的就是首先激活或选择一个工作表,然后您所做的任何单元格引用都将针对您已激活或选择的工作表中的单元格。我在这里要疯了吗?