运行以下代码的第一行后,Excel 将更改用户界面中的"匹配整个单元格内容"设置。结果是,下次用户按 Ctrl+F 时,将在整个单元格内容中完成搜索。我不喜欢更改影响用户体验的设置的 VBA 宏,所以我总是执行第二行,它会执行另一次搜索并将"匹配整个单元格内容">设置回默认值。
'execute the find and changes the entire cell content setting
Set C = MyRange.Find(SomeText, LookAt:=xlWhole)
'put the setting back to the default value (not the previous value)
MyRange.SomeText ParName, LookAt:=xlPart
问题是它将其设置回默认值,而不是用户最后设置的值。
我宁愿有这样的东西:
'store the current entire cell content setting
OldLookAt = Application.FindLookAt
'execute the find
Set C = MyRange.Find(SomeText, LookAt:=xlWhole)
'restore the original setting
Application.FindLookAt = OldLookAt
我编造了Application.FindLookAt
,因为我找不到它。
有没有办法在不影响用户体验的情况下Range.Find
某些东西?
我花了相当多的时间浏览 Excel 对象库和 MSDN 文档,似乎无法检索。
不幸的是,如果您未将参数包含在默认值中,Excel 实际上也会覆盖并设置您的用户设置。
Private Sub testXLLookAT()
'Setup fake falues
Dim mCurLookup As XlLookAt
Range("A1").value = "Test1"
Range("A2").value = "Test"
'get current setting, but this doesn't work as it defaults...
If Range("A1:A2").Find("Test").Address = "A1" Then
mCurLookup = xlPart
Else
mCurLookup = xlWhole
End If
'your find here
'note - mCurLookup always becomes xlWhole...
Range("A1:A2").Find What:="Test", LookAt:=mCurLookup
End Sub
否则,上面的代码将起作用 - 但它不会,因为即使不包含默认值也会被覆盖。
下面是一个函数,可用于返回当前的 LookAt 默认值,以便可以重置它。
Function lGetCurLookAt() As Long
'--returns current default value for Range.Find method's
' LookAt parameter.
'--use helper cell after all data in col A
With Cells(Rows.Count, "A").End(xlUp)(3)
.Value = "TestPart"
lGetCurLookAt = IIf( _
.Find(What:="Part", SearchFormat:=False) Is Nothing, _
xlWhole, xlPart)
.Value = vbNullString
End With
End Function
我的第一篇文章,所以我无法对恩德兰的答案添加评论。本着乐于助人的精神,该代码没有按预期工作,因为它使用 A1 而不是 $A$1。