下标超出范围 - 使用Excel VBA查找下一个
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了下标超出范围 - 使用Excel VBA查找下一个相关的知识,希望对你有一定的参考价值。
我在此行收到“下标超出范围”错误消息:
Set NextRow = Sheets(xSheet).Cells.FindNext(After:=bookmark)
理论上我在设置foundCell的那一刻就设置了我的书签。
我想:
- 搜索与“Str”变量中的文本匹配的第一条记录。
- 使用Excel的查找功能,查找文本及其所在的行,并根据单元格值填充用户表单
- 计算总结果,这样我就可以在用户表单的某处找到[1] [3]
- 使用按钮向后搜索(上一页和下一页)我的搜索结果。
'Global Variables
Dim foundCell
Dim bookmark
Private Sub btnSearch_Click()
Dim Str
Dim FirstAddr
Dim xSheet
xSheet = "Office Spaces"
Str = "B-32"
With Sheets(xSheet)
Set foundCell = .Cells.Find(What:=Str, After:=.Cells(1, 1), _
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
Set bookmark = foundCell
End With
If Not foundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & foundCell.Row)
UserForm1.location.Text = Sheets(xSheet).Cells(foundCell.Row, 3).Value
UserForm1.office.Value = Sheets(xSheet).Cells(foundCell.Row, 2).Value
UserForm1.floor.Value = Sheets(xSheet).Cells(foundCell.Row, 1).Value
UserForm1.status.Value = Sheets(xSheet).Cells(foundCell.Row, 4).Value
UserForm1.telephone.Value = Sheets(xSheet).Cells(foundCell.Row, 5).Value
UserForm1.mobile.Value = Sheets(xSheet).Cells(foundCell.Row, 6).Value
UserForm1.owner.Value = Sheets(xSheet).Cells(foundCell.Row, 7).Value
UserForm1.notes.Value = Sheets(xSheet).Cells(foundCell.Row, 8).Value
UserForm1.recnum.Value = 1
FirstAddr = foundCell.Address
Dim i
Do Until foundCell Is Nothing
Set foundCell = Sheets(xSheet).Cells.FindNext(After:=foundCell)
i = i + 1
If foundCell.Address = FirstAddr Then Exit Do
Loop
If i > 1 Then
btnPrev.Enabled = True
btnNext.Enabled = True
End If
UserForm1.recmax.Value = i
Else
MsgBox ("Bingo not found")
End If
End Sub
Private Sub btnNext_Click()
Dim NextRow
Set NextRow = Sheets(xSheet).Cells.FindNext(After:=bookmark)
UserForm1.location.Value = Sheets(xSheet).Cells(NextRow.Row, 3).Value
UserForm1.office.Value = Sheets(xSheet).Cells(NextRow.Row, 2).Value
End Sub
答案
错误是由xSheet
未分配适当的值引起的。为什么它没有价值?因为它是在一个Sub中定义和分配的,并在另一个Sub中使用。解决这个问题的一种方法是使xSheet
像bookmark
那样全球化。
最好还要考虑其他评论的建议。这些建议可以改善您的代码。
以上是关于下标超出范围 - 使用Excel VBA查找下一个的主要内容,如果未能解决你的问题,请参考以下文章