我試圖將工作表從主工作簿複製到目標工作簿,但根據rngCurrent中的值是否存在於工作表名稱中,我複製的工作表是不同的。出於某種原因,我在最後一行不斷收到下標或範圍錯誤。任何人都可以幫助我理解發生了什麼?複製動態數組導致下標超出範圍錯誤
Sub test2()
Dim wb As Workbook
Dim master As Workbook
Dim wbCurrent As Workbook
Dim wbAdjustments As Workbook
Dim wsName As Worksheet
Dim rngEntityList As Range
Dim rngCurrentEntity As Range
Dim rngCurrent As Range
Dim arrWorksheets As Variant
Dim i As Integer
Dim wsCount As Integer
Set master = ThisWorkbook
Set rngCurrentEntity = master.Sheets("File Info").Range("rng_Entity") 'named range of single entity
Set rngEntityList = master.Sheets("Global").Range("rng_EntityList") 'list or entities
Set rngCurrent = rngEntityList.Find(rngCurrentEntity.Value, LookIn:=xlValues) ' find single entity in the list
If rngCurrent.Offset(, 4).Value = "FRP" Then 'find if it's FRP
Set wb = Application.Workbooks("Foreign.xlsx")
Else
Set wb = Application.Workbooks("Domestic.xlsx")
End If
Dim ws() As String ' declare string array
ReDim ws(wb.Worksheets.Count) As String ' set size dynamically
Dim counter As Long ' running counter for ws array
counter = 1
For i = 1 To wb.Worksheets.Count
If InStr(1, wb.Worksheets(i).Name, rngCurrent.Value) <> 0 Then
ws(counter) = wb.Worksheets(i).Name
counter = counter + 1
End If
Next
ReDim Preserve ws(counter) As String ' Get rid of empty array entries
wb.Worksheets(ws).Copy After:=master.Worksheets(master.Worksheets.Count)
End Sub
編輯 我之所以要做這樣說是因爲我不想讓外部鏈接到源的筆記本電腦。
什麼都行,你讓你的錯誤? –
默認情況下,數組的下限爲零,而不是一個。你的錯誤是從陣列的第0個槽中沒有內容。嘗試使用'ReDim ws(1 to wb.Worksheets.Count)'(指定上下邊界,不帶'As String) –
@ShaiRado我在wb.Worksheets(ws).Copy行 –