我正在尝试将当前活动选择转换为命名范围,我可以将其引用为数据透视表的数据源。我的函数selectByUsedRows根据usedCol中的行数以及selectStartCol和selectEndCol的启动和停止提供选择。当您只希望选择包含与选择范围之外的列的行数相匹配的单元格时,这非常有用。我对这个选项的命名没有深入的了解。任何帮助都会很棒。
Excel数据
A B C
1 CaseNum Branch Name
2 1234 APL George
3 2345 VMI George
4 3456 TEX Tom
5 4567 NYC Tom
6 5678 VMI Sam
7 6789 TEX Tom
8 7890 NYC George
VBA
'Check reference column and select the same number of rows in start and end columns
Sub selectByUsedRows(usedCol As String, selectStartCol As String, selectEndCol As String)
n = Range(usedCol & "1").End(xlDown).Row
Range(selectStartCol & "1:" & selectEndCol & n).Select
End Sub
'Dynamically select columns A to C with as many rows as are in A
Sub test()
refCol = "A"
selectStartCol = "A"
selectEndCol = "C"
selectByUsedRows refCol, selectStartCol, selectEndCol
'Code works until this point. There is now an active selection of A1:C8.
'The following is hypothetical
Dim rngSelection As Range
Set rngSelection = ActiveSelection
Range(rngSourceData).CurrentRegion.Name = "rngSourceData"
Set objTable = Sheet5.PivotTableWizard
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
rngSourceData, Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Sheet5!R1C4", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion14
End Sub
答案 0 :(得分:1)
我假设您正在努力让数据透视表基于'代码工作直到这一点'
以下提示输入范围,然后在新工作表上提供基本数据透视表大纲
Option Explicit
Private Sub someControlOrEvent_Click()
Dim rRange As Range
Dim pTable As Worksheet
On Error Resume Next
Set rRange = Application.InputBox(prompt:= _
"Please select a new data range to name", _
Title:="SPECIFY RANGE", Type:=8)
On Error GoTo 0
If rRange Is Nothing Then
Exit Sub
Else
'Define Named Range (but not used any further)
ThisWorkbook.Names.Add Name:="MyRange", RefersTo:=rRange
Set pTable = ThisWorkbook.Sheets.Add
ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
rRange, Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:=pTable.Range("A1"), TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion14
End If
End Sub
在这种情况下,rRange
是您想要的任何范围,如本例所示的提示,或者可以是命名范围,当前选择等。它还假设数据透视表在新工作表的单元格A1中开始。 / p>