这很奇怪。根据MSDN(以及StackOverflow上的几个问题),当在指定范围内找不到指定值时,VBA中的Range.Find方法应返回Nothing
。但是,当我运行以下代码时,如果未找到该值,则Range.Find方法不会返回Nothing
。它不会返回任何。
请假设所有变量都已正确定义。 VBA位于Access 2013模块中,引用了Microsoft Office 15.0对象库。
Dim rng As Excel.Range
Dim rngFound As Excel.Range
' ...
For i = 0 To UBound(strHeader)
Set rngFound = rng.Find( _
What:=strHeader(i), _
After:=rng(rng.Cells.Count), _
LookAt:=xlWhole, _
MatchCase:=True _
)
If rngFound Is Nothing Then
bolValid = False
Exit For
ElseIf i = UBound(strHeader) Then
bolValid = True
End If
Next i
如果在strHeader(i)
范围内找不到rng
中的字符串,则变量rngFound
应设置为Nothing
。但是,事实并非如此。
假设早期迭代中rngFound.Address
的值为“$ J $ 1”。现在假设在rng
中找不到当前迭代的值。 Range.Find 应返回Nothing
,但在立即窗口中查询时,rngFound.Address
仍然是“$ J $ 1”。
知道可能导致这种奇怪行为的原因是什么?
编辑:根据要求提供完整的功能代码。
Private Function CheckIntegrity(FileName As String) As Boolean
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim rng As Excel.Range
Dim rngFound As Excel.Range
Dim strHeader() As String
Dim i As Integer
Dim bolValid As Boolean
On Error GoTo PROC_ERR
ReDim strHeader(9)
strHeader(0) = "String1"
strHeader(1) = "String2"
strHeader(2) = "String3"
strHeader(3) = "String4"
strHeader(4) = "String5"
strHeader(5) = "String6"
strHeader(6) = "String7"
strHeader(7) = "String8"
strHeader(8) = "String9"
strHeader(9) = "String10"
Set wb = OpenWorkbook(FileName, True)
If Not wb Is Nothing Then Set ws = wb.Worksheets(1)
If Not ws Is Nothing Then Set rng = ws.Range("A1:Z1")
If Not rng Is Nothing Then
For i = 0 To Ubound(strHeader)
Set rngFound = rng.Find( _
What:=strHeader(i), _
After:=rng(rng.Cells.Count), _
LookAt:=xlWhole, _
MatchCase:=True _
)
If rngFound Is Nothing Then
bolValid = False
Exit For
ElseIf i = Ubound(strHeader) Then
bolValid = True
End If
Next i
End If
wb.Close SaveChanges:=False
CheckIntegrity = bolValid
PROC_EXIT:
Set wb = Nothing
Set ws = Nothing
Set rng = Nothing
Set rngFound = Nothing
Erase strHeader
i = 0
bolValid = False
Exit Function
PROC_ERR:
MsgBox "Error encountered. " & Err.Number & " " & Err.Description
Resume PROC_EXIT
End Function
如果找不到strHeader的元素,则rngFound的值不会设置为Nothing
。
答案 0 :(得分:0)
class_weight
以上对我有用。我不得不添加Microsoft Excel引用以使用Excel.Range等试一试。
由于
答案 1 :(得分:0)
解决。在弹出一些其他错误之后,我在Windows控制面板中对我的Microsoft Office安装执行了“修复”,这个问题的问题显然已经解决了。与上面相同的代码现在工作正常。
感谢所有人的帮助,但我认为这只是一个pooched Office安装问题。