gpt4 book ai didi

excel - 用 Range.Find 一无所获

转载 作者:行者123 更新时间:2023-12-04 07:59:39 25 4
gpt4 key购买 nike

我已经阅读了文档并且一直在使用该方法并取得了不同程度的成功,但我一直遇到我正在寻找的对象显然就在那里但 Range.Find 什么也不返回的情况。

test = Search_Range.Cells(4,4).Value = Search_Text 'returns true
set test2 = Search_Range.Find(What:=Search_Text) 'returns nothing
我很沮丧!目标单元格在 Search_Range 内。 Search_Range 在正确的工作表上。该值的数据类型与 Search_Text 相同。即使我添加了 LookAt:=xlPart 或 LookAt:=xlWhole 之类的东西,也没有任何变化。与 LookIn:=xlValues 相同。
还有哪些其他来源可能导致该方法不返回任何内容?
这是导致我扯掉头发的功能。我这样做是为了让用户可以快速识别宏找不到的内容。
Private Function Look_For(ByVal Search_Text As String, ByRef Search_Range As Range, _
Optional LookAt As Long = xlPart, _
Optional Error_Message As Boolean = True) As Variant
On Error Resume Next
Set Look_For = Search_Range.Find(What:=Search_Text, LookAt:=LookAt, MatchCase:=False)
On Error GoTo 0

If Look_For Is Nothing Then
Look_For = False
If Error_Message = True Then MsgBox "Could not find """ & Search_Text & _
""" in the area " & Search_Range.Address & "." & vbNewLine & _
"Please fix the sheet or this macro and try again.", _
vbCritical, "Fatal Error!"
End If

End Function
编辑:
这是一个可以重新创建问题的子程序。
Sub Test()
Const Txt As String = "FSQP 4.16-04F Skid Detail Sheet"
Dim target As Range
If Not Look_For(Txt, Sheet1.Range("A1:D8")) = False Then
Set target = Look_For(Txt, Sheet1.Range("A1:D8"))
End If
If target Is Nothing Then MsgBox "Minimal Reproducible Example"
End Sub
没有错误消息,我只是想使用 Range.Find 获取一个单元格对象并将其保存到一个变量中,但我没有从 Range.Find 获得任何信息
my spreadsheet

最佳答案

感谢 John Coleman、BigBen 和 Tim Williams 的建议,我能够找到这个问题的答案。
问题是 Range.Find 无法处理部分超出定义范围的合并单元格。我们在 D4 中寻找的单元格实际上是合并的 D4:F4。为了避免这个问题,我在执行 Range.Find 之前编辑了函数以检查和扩展搜索范围。
这是修改后的功能

Private Function Look_For(ByVal Search_Text As String, ByRef Search_Range As Range, _
Optional LookAt As Long = xlPart, _
Optional Error_Message As Boolean = True) As Variant

Dim oCell As Range, mCell As Range
For Each oCell In Search_Range
If oCell.MergeCells = True Then
For Each mCell In oCell.MergeArea
If Intersect(mCell, Search_Range) Is Nothing Then
Set Search_Range = Union(Search_Range, oCell.MergeArea)
End If
Next mCell
End If
Next oCell

Set Look_For = Search_Range.Find(what:=Search_Text, LookAt:=LookAt, MatchCase:=False)

If Look_For Is Nothing Then
Look_For = False
If Error_Message = True Then MsgBox "Could not find """ & Search_Text & _
""" in the area " & Search_Range.Address & "." & vbNewLine & _
"Please fix the sheet or this macro and try again.", _
vbCritical, "Fatal Error!"
End If

End Function
在 Tim Williams 的建议下,我删除了 On Error Resume Next 和 On Error Goto 0,它们是不必要的。

关于excel - 用 Range.Find 一无所获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66537259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com