错误9 VBA - 每隔一次运行就会出现超出范围的下标

时间:2016-03-29 19:34:55

标签: excel vba excel-vba ms-access access-vba

位于我的访问数据库中的以下代码在一半的时间内运行正常。另一半它给了我:"错误9下标超出范围,"并突出显示"设置WKS =工作簿(..."行作为问题。我知道问题在于它不确定它引用哪个工作簿。但是我不知道是什么要做得更清楚。

Sub fixborderss()
Dim WKS As Excel.Worksheet
Dim lastrow As Long


Set WKS = Workbooks("L3 PSR.xls").Worksheets("L-3 Project Status Report")

lastrow = Range("I" & WKS.Rows.Count).End(xlUp).Row

WKS.Range("A8:V" & lastrow).Borders(xlEdgeTop).Color = RGB(191, 191, 191)
WKS.Range("A8:V" & lastrow).Borders(xlEdgeBottom).Color = RGB(191, 191, 191)
WKS.Range("A8:V" & lastrow).Borders.LineStyle = xlContinuous

End Sub

1 个答案:

答案 0 :(得分:1)

根据代码的构造方式,您有几个选项:

1)使XL成为公共变量:

Public XL As Excel.Application '// Declare at top of module, outside of any subs/functions

2)将Excel传递给另一个子:

Set XL = New Excel.Application
'// ... more code

My_Other_Sub XL '// Call sub and pass Excel object

'// Some more code

End Sub

Public Sub My_Other_Sub(ByRef XL As Excel.Application)
    Set ws = XL.Workbooks(1).Sheets(1)
    '// Other code
End Sub

3)如果Excel已经打开,请使用GetObject()方法。

Set XL = GetObject(, "Excel.Application")

If Not XL Is Nothing Then
    Set ws = XL.Workbooks(1).Sheets(1)
End If