遇到运行时错误9激活特定工作簿时下标超出范围

时间:2018-09-02 08:16:35

标签: excel vba excel-vba

我尝试了先前问题中的所有建议,但没有成功,并花费了大量时间,但没有找到正确的解决方法。

如图所示,当我尝试激活Workbook1(Work.xlsm)的“ Sheet1”表时,出现运行时错误(即使没有拼写错误)。但是它可以从另一个工作簿(Book1.xlsx)运行,将Excel工作表(LS)数据填充到UserForm组合框和文本框上也没有问题。

现在我的问题是,当我单击“添加”按钮时,用户表单数据正在工作簿(Book1.xlsx)excel工作表(LS)上填充,而我希望它在工作簿1(Work.xlsm)的“ Sheet1”工作表上填充

为此,我尝试调用Workbook1(Work.xlsm)的主“ Sheet1”工作表,但尝试激活时出现错误。您能帮我解决这个问题吗? 图片在这里:Error in this lineRun time error; From range A8 it should start populating(desired ouput in workbook1)

下面是我的组合框更改和命令按钮(ADD)代码:

Private Sub cboLs_Change()
Dim i As Long, LastRow As Long, ws As Worksheet
Dim wb As Workbook
Set wb = Workbooks.Open("C:\Users\Desktop\Book1.xlsx")
Set ws = wb.Worksheets("LS")
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Val(Me.cboLs.Value) = ws.Cells(i, "A") Then
MsgBox Me.cboLs.Value
Me.txtProject = ws.Cells(i, "B").Value
End If
Next i
End Sub


Private Sub cmdadd_Click()
    Dim i As Integer
    Dim wb As Workbook
    Dim ws1 As Worksheet
    Set wb = Workbooks.Open("C:\Users\Desktop\Work.xlsm")
    wb.Activate
    Set ws1 = wb.Worksheets("Sheet1")
    Worksheets("Sheet1").Activate
    'position cursor in the correct cell A2.
    ActiveSheet.Range("A8").Select
    Do Until ActiveCell.Value = Empty
        ActiveCell.Offset(1, 0).Select 'move down 1 row
        i = i + 1 'keep a count of the ID for later use
    Loop
    'Populate the new data values into the 'Data' worksheet.
    ActiveCell.Value = i 'Next ID number
    'Populate the new data values into the 'Data' worksheet.
    ws1.Range("A6").Value = e 'Next ID number
    ws1.Range("B6").Value = Me.txtname.Text 'set col B
    ws1.Range("C6").Value = Me.txtbook.Text 'set col C
    ws1.Range("D6").Value = Me.cboLs.Text
 End Sub


 Private Sub UserForm_Initialize()
    Dim i As Long, LastRow As Long, ws As Worksheet
    Dim wb As Workbook
    Set wb = Workbooks.Open("C:\Users\Desktop\Book1.xlsx")
    Set ws = wb.Worksheets("LS")
    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
    For i = 2 To LastRow
    Me.cboLs.AddItem ws.Cells(i, "A").Value
    Next i
 End Sub

1 个答案:

答案 0 :(得分:0)

非常简单:

Set ws1 = wb.Worksheets("Sheet1")引发Subscript out of Range错误,因为文件“ C:\ Users \ Desktop \ Work.xlsm中没有名称为” Sheet1“ 的工作表。 “

您正在通过WorkSheet对象的Name进行引用,这就是小标签上显示的内容。在VBA中,对象很可能就是对象浏览器中的“ Sheet1”:

  • 在这种情况下,您可以使用Set ws1 = wb.Sheet1
  • 如果要使用名称,请检查Excel GUI中的选项卡,然后使用Set ws1 = wb.Worksheets("Whatever is displayed on the little tab at the bottom of your screen")

有关如何参考图纸的一些示例,请阅读this