繁体   English   中英

如何从另一个工作簿引用源数据 - 下标超出范围

[英]How to reference source data from another workbook - subscript out of range

我有一个仪表板(工作表“仪表板”),其中包含一组数据透视表,这些数据集依赖于同一工作簿的特定工作表(工作表“仪表板数据”)上的动态数据集。 当前提示用户选择带有原始数据的工作表上的单元格(由于可能的工作表名称不同),然后宏将仪表板数据表上的必要数据组合在一起并更新数据透视表。 只要原始数据位于同一工作簿中的工作表上,就可以正常工作。

我正在尝试找到一种解决方案,以便用户可以选择不在同一工作簿中的工作表上的原始数据。 当我按原样运行它时,我得到一个下标超出范围的错误。

Option Explicit
Sub HB_Run_Dashboard()

Dim Ws As Worksheet, lastRow As Long
Dim myNamedRange As Range, Rng As Range, c As Range, destrange As Range
Dim myRangeName As String
Dim desiredSheetName As String
Dim SearchRow As Long
Dim StartatRow As Long
Dim pvt As PivotTable
Dim S As String

'user prompt to locate cell in the sheet with the raw data to capture sheet name

desiredSheetName = Application.InputBox("Select any cell inside the source sheet: ", _
"Prompt for selecting target sheet name", Type:=8).Worksheet.Name

'currently a test code to also have the user find the location of the sheet

'Inputsheetpath = Application.GetOpenFilename(FileFilter:= _
"Excel Workbooks (*.xls*),*.xls*,*.xlsb,*.xlsm", Title:="Open Database File")

'this is where i am stuck. how to set the WS with the correct path info to avoid subscript out of range
Set Ws = Workbook.Worksheets(desiredSheetName)

SearchRow = InputBox("Row # where Reference 'Dashboard' is entered.", "Row Input")
StartatRow = InputBox("Row # where Headers are located.", "Row Input")

'Const SearchRow As Long = SRow
'Const StartAtRow As Long = StRow
Const RangeName As String = "Dashboard_Data_Raw"

lastRow = Ws.Cells(Ws.Rows.Count, "A").End(xlUp).Row

'loop cells in row to search...
For Each c In Ws.Range(Ws.Cells(SearchRow, 1), _
                       Ws.Cells(SearchRow, Columns.Count).End(xlToLeft)).Cells
    If LCase(c.Value) = "dashboard" Then 'want this column
        'add to range
        BuildRange myNamedRange, _
            Ws.Range(Ws.Cells(StartatRow, c.Column), Ws.Cells(lastRow, c.Column))
       
    End If
Next c

Debug.Print myNamedRange.Address
Worksheets(desiredSheetName).Names.Add Name:=RangeName, RefersTo:=myNamedRange

代替:

Dim desiredSheetName As String
desiredSheetName = Application.InputBox("Select any cell inside the source sheet: ", _
                   "Prompt for selecting target sheet name", Type:=8).Worksheet.Name

你可以这样做:

Dim desiredSheet As Worksheet
Set desiredSheet = Application.InputBox("Select any cell inside the source sheet: ", _
                   "Prompt for selecting target sheet name", Type:=8).Worksheet

然后desiredSheet是对用户选择的工作表的引用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM