vba - 选择工作簿时下标超出范围

标签 vba excel compiler-errors

当我试图让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

最佳答案

首先,最好使用完整的文件名: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

关于vba - 选择工作簿时下标超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44886962/

相关文章:

vba - 默认情况下如何在 Outlook 中放置边框圆形图像

r - 在 Excel VBA 中运行 RScript 时出错

excel - 将复选框控件暗淡设置为用户窗体复选框

objective-c - 在将属性移动到 .h 文件后,ARC 不允许将 Objective-C 指针隐式转换为 'int *'

c++ - 我在 C++ 中创建阻塞队列 vector 时遇到问题

events - 用户表单中的事件顺序

Java:byte[] 数组到 Excel 到 BLOB

excel - 如何使用 vbscript 查找 Excel 中特定值的行号

java - 使用 Apache POI 删除 HSSF 表的数据验证

visual-studio-2010 - Visual Studio 2010 C++发行模式问题