下标超出范围运行时错误9

时间:2014-07-10 00:22:02

标签: excel-vba vba excel

我正在创建一个函数,从两个excel文件中读取列标题,然后将这些列标题放在复选框中,以便用户可以检查他将使用哪些列。当我使用一个文件时,它可以工作,但是当我修改它以使用两个文件时,我得到"运行时错误9:下标超出范围"并突出显示line =>设置wks2 = ActiveWorkbook.Worksheets(SheetName2)。

即使有这个错误消息仍然适用于第一个文件,但它不适用于第二个文件。有人可以帮我找到这个错误信息的原因吗?非常感谢你提前。

 Function CallFunction(SheetName1 As Variant, SheetName2 As Variant) As Long
' This is a function used to retrieve column titles and place them as checkboxes in a listBox

 Dim jTitles(200) As String
 Dim sTitles(200) As String
 Dim titless As Integer
 Dim titlesj As Integer
 Dim wks1 As Worksheet
 Dim wks2 As Worksheet
 Dim Item(200) As String

 SPathName = Range("F18").Value
 SFilename = Range("F19").Value

 JPathName = Range("F22").Value
 JFilename = Range("F23").Value

 Workbooks.Open Filename:=SPathName & "\" & SFilename
 Workbooks.Open Filename:=JPathName & "\" & JFilename

 Set wks1 = ActiveWorkbook.Worksheets(SheetName1)

 For j = 1 To 199
     If Trim(wks1.Cells(4, j).Value) = "" Then
        titlesj = j - 1
        Exit For
    End If
        jTitles(j - 1) = wks1.Cells(4, j).Value
 Next

 j = 1

 ' Add column titles from files into the listbox as checkboxes
 For j = 0 To titlesj
    Sheet1.ListBox1.AddItem jTitles(j)
    Sheet1.ListBox3.AddItem jTitles(j)
 Next

 Set wks2 = ActiveWorkbook.Worksheets(SheetName2)  ' <=== HERE POPS THE ERROR MESSAGE

 For s = 1 To 199
    If Trim(wks2.Cells(1, s).Value) = "" Then
        titless = s - 1
        Exit For
    End If
        sTitles(s - 1) = wks2.Cells(1, j).Value
 Next

 s = 1

 For s = 0 To titless
    Sheet1.ListBox2.AddItem sTitles(s)
    Sheet1.ListBox4.AddItem sTitles(s)
 Next

    Workbooks(JFilename).Close
    ' Workbooks(SFilename).Close

End Function

1 个答案:

答案 0 :(得分:1)

当工作簿Worksheets集合中不存在指定的工作表名称时,会出现下标超出范围错误。

我注意到你有两个打开的工作簿:

Workbooks.Open Filename:=SPathName & "\" & SFilename
Workbooks.Open Filename:=JPathName & "\" & JFilename

但是,您的两个工作表作业仅指ActiveWorkbook

错误的原因当然是SheetName2中不存在ActiveWorkbok(由JFilename指定)

特别是在使用多本书籍或工作表时,it is always preferable to avoid using Activate/Select methods - 否则您需要跟踪哪个工作簿/工作表/等。是&#34;活跃&#34;,这使得意大利面条代码和许多不必要的.Activate方法调用。

知道 SheetName1中存在JFilename,我假设工作簿SheetName2中存在SFileName

相反,定义两个Workbook变量:

Dim wb1 as Workbook
Dim wb2 as Workbook

Workbooks.Open方法的结果分配给这些工作簿:

Set wb2 = Workbooks.Open(Filename:=SPathName & "\" & SFilename)
Set wb1 = Workbooks.Open(Filename:=JPathName & "\" & JFilename)

现在,wb1是&#34;有效&#34;工作簿,以及工作表分配:

Set wks1 = wb1.Worksheets(SheetName1)

以后为Sheetname2

Set wks2 = wb2.Worksheets(Sheetname2)

否则,您的工作表名称或您要发送到此功能的字符串参数中会出现拼写错误。仔细检查/调试SheetName2的值是否正确它是否存在。