【发布时间】:2015-10-24 18:06:32
【问题描述】:
首先,如果这个问题太明显,我提前道歉。我只是几年没有使用过 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)
为什么需要添加
“表格(“报告”)。”
?我以为最后一个激活的工作表是“报告”。因此,如果我使用:
使用单元格(行,列)
单独 - 不应该自动引用
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
第二个例子有什么问题?它快把我逼疯了。我认为您所要做的就是首先激活或选择一个工作表,然后您在此之后所做的任何单元格引用都将用于您已激活或选择的工作表中的单元格。我要疯了吗?
【问题讨论】:
-
代码在这里按预期工作——即使没有明确的引用。 1. 在循环前插入
Application.EnableEvents = False,检查是否有宏干扰。 2.在ItemName=...行和单步(F8)处设置断点,每步后在直接窗口中检查?activesheet.name。 -
试试
Worksheets("Report").Activate,而不是ReportSheet.Activate。如果您仍需要工作表引用,请使用ReportSheet对象而不是Sheets("Report")。 -
user1016274 感谢您的帮助!