[英]Subscript out of range error when copying data from a workbook to another
[英]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.