2017-07-03 55 views
0

當我試圖讓Excel選擇使用哪個工作簿時,它給我一個下標超出範圍的錯誤。我不知道我是否必須引用它來自哪個文件夾。他們都在同一個文件夾中。我研究過其他人的解決方案,但我沒有相同的格式和任務。該錯誤是在那裏分配工作簿的數字當選擇工作簿時下標超出範圍

Sub bringbookstogether() 

Dim currentsheet As Worksheet 
Set currentsheet = Application.ActiveSheet 

Dim othersheets As Worksheet 

Dim wbook As Workbook 

Dim c As String 

'assigns the number to start with 

Dim a, b, d As Integer 

a = 4 
b = 6 
d = 1 

'assigns workbook numbers 
If (d = 1) Then 
    Set wbook = Workbooks("MaintPrep Sheet 1st") 
    Else 
    If (d = 2) Then 
     Set wbook = Workbooks("MaintPrep Sheet 2nd") 
     Else 
     If (d = 3) Then 
      Set wbook = Workbooks("MaintPrep Sheet 3rd") 
     End If 
    End If 
End If 

'End if it's done with all the workbooks 

Do Until (d = 4) 

'Looks for the sheet that has the same name 

Do While (c = currentsheet.Name) 

'Ends in row 99 

Do While (b < 99) 

'Ends in Column 52 

Do While (a < 52) 

currentsheet.Cells(b, a) = currentsheet.Cells(b, a) + Workbooks(d).Sheets(c).Cells(b, a) 

a = a + 1 
Loop 

b = b + 1 
Loop 

Loop 

d = d + 1 
Loop 

End Sub 

回答

0

首先的線,這是更好地使用完整的文件名: Workbooks("MaintPrep Sheet 1st.xlsx")

其次重要的是,這個代碼將盡快爲一個錯誤您嘗試訪問的工作簿當前未打開。如果工作簿是不開放的,它不會在當前環境中存在,因此Excel將拋出錯誤91.

爲了解決這個問題,你可以這樣做:

Sub a() 
Dim wb As Workbook 

On Error Resume Next 'To avoid error 91 
Set wb = Workbooks("MaintPrep Sheet 1st.xlsx") 
On Error GoTo 0 'To avoid not seeing other errors. 

If Not wb Is Nothing Then 
    'Do stuff 
    MsgBox "Opened!" 
Else 
    'Handle the fact that it's missing 
    MsgBox "Not open!" 
End If 

'Alternatively, OPEN the workbook if you couldn't set it in the first place: 
On Error Resume Next 
Set wb = Workbooks("MaintPrep Sheet 1st.xlsx") 
On Error GoTo 0 

If wb Is Nothing Then 
    Set wb = Workbooks.Open("C:\FullPath\MaintPrep Sheet 1st.xlsx") 
    'Do stuff 
End If 

End Sub 
+0

我必須做一個對每個工作簿? – MaxAttack102

+0

取決於您的用例。你也可以假設默認關閉工作簿,並在設置wbook變量時使用'Workbooks.Open(「path \ filename.xlsx」)'。 –

+0

沒有錯誤,謝謝。 – MaxAttack102