2017-07-03 57 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