現在のアクティブな選択範囲を、ピボット テーブルのデータ ソースとして参照できる名前付き範囲に変換しようとしています。私の関数 selectByUsedRows は、usedCol 内の行数に基づいて選択を提供し、selectStartCol と selectEndCol で開始および停止します。これは、選択範囲外にある列の行数と一致するセルのみを選択範囲に含めたい場合に便利です。このセレクションに名前を付けるには深みがありません。どんな助けでも素晴らしいでしょう。
エクセルデータ
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