有时我的 VBA 函数 FindInRow 有效,有时则无效。
VBA 函数 FindInRow 用于查找 Excel 行中是否存在“文本”。如果在行中找到文本,该函数应返回找到文本的列号。如果未找到文本,则应返回 0。
一切正常 - 除非搜索的文本类似于日期。请参阅我的子例程 (TestFindInRow),它显示何时有效、何时无效。
使用 VBA 从字符串变量插入行中的文本,其中包含大部分但并不总是类似于日期的数据。
可能是什么原因以及如何搜索类似于日期的字符串变量?我希望我的函数 FindInRow 在行中的单元格包含文本或日期时都能工作。有解决办法吗?
Function FindInRow(ws As Worksheet, row As Long, s As String) As Long 'Return col
Dim Cell As Range
Set Cell = ws.Rows(row).Cells.Find(What:=s, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Cell Is Nothing Then
FindInRow = 0
Else
FindInRow = Cell.Column
End If
End Function
Sub TestFindInRow()
Dim i As Integer
Const sd As String = "2024-05-" 'Date ?
Const ss As String = "XXXX-05-" 'String
For i = 1 To 20
ActiveSheet.Cells(1, i) = sd & i
Next i
'Test cell value type = Date ? > Not working
Debug.Print FindInRow(ActiveSheet, 1, sd & 10)
Debug.Print FindInRow(ActiveSheet, 1, sd & "10")
For i = 1 To 20
ActiveSheet.Cells(1, i) = ss & i
Next i
'Test cell value type = String > Working
Debug.Print FindInRow(ActiveSheet, 1, ss & 10)
Debug.Print FindInRow(ActiveSheet, 1, ss & "10")
End Sub
如果
s
看起来像日期,那么您可以在将其传递给 Find()
之前将其转换为日期:否则,搜索提供的值:
Function FindInRow(ws As Worksheet, row As Long, s As String) As Long 'Return col
Dim Cell As Range, v
FindInRow = 0 'default return value
v = s
If IsDate(v) Then v = CDate(v) 'if looks like a date, convert to date
Set Cell = ws.Rows(row).Cells.Find(What:=v, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not Cell Is Nothing Then FindInRow = Cell.Column
End Function