您可以检查您正在查找的数据的值和类型以及搜索区域中的数据,然后在必要时转换您正在查找的数据。第一个选项,搜索不同类型的数据,没有找到Date(考虑locale)。在第二个变体中,Date 被转换为 String(考虑语言环境)并且搜索成功。
选项 1
Sub test1()
Date_vars_array = Array(20211207#, 20211207, "20211207", #12/7/2021#) ' or #7/12/2021# for your locale
For Each Date_var In Date_vars_array
With NewSheet.Range("B5:BL5")
.NumberFormat = "yyyymmdd"
Set Columnfind = .Find(What:=Date_var, LookIn:=xlValues, lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Columnfind Is Nothing Then
colnum = 0
Else
colnum = Columnfind.Column
End If
End With
Debug.Print ".Finding for 'Date_var = " & Date_var & "' which has '" & TypeName(Date_var) & "' data type:"
Debug.Print vbTab & "'NewSheet.Range(""B5"") = " & NewSheet.Range("B5").Value & "' and has '" & TypeName(NewSheet.Range("B5").Value) & "' data type"
Debug.Print vbTab & "'colnum = " & colnum & "'" & vbLf
Next
End Sub
输出 1
.Finding for 'Date_var = 20211207' which has 'Double' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 2'
.Finding for 'Date_var = 20211207' which has 'Long' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 2'
.Finding for 'Date_var = 20211207' which has 'String' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 2'
.Finding for 'Date_var = 07.12.2021' which has 'Date' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 0'
选项 2(如果 TypeName(Date_var) = "Date" Then Date_var = Format(Date_var, "yyyymmdd") 添加)
Sub test1()
Date_vars_array = Array(20211207#, 20211207, "20211207", #12/7/2021#) ' or #7/12/2021# for your locale
For Each Date_var In Date_vars_array
With NewSheet.Range("B5:BL5")
.NumberFormat = "yyyymmdd"
If TypeName(Date_var) = "Date" Then Date_var = Format(Date_var, "yyyymmdd")
Set Columnfind = .Find(What:=Date_var, LookIn:=xlValues, lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)
If Columnfind Is Nothing Then
colnum = 0
Else
colnum = Columnfind.Column
End If
End With
Debug.Print ".Finding for 'Date_var = " & Date_var & "' which has '" & TypeName(Date_var) & "' data type:"
Debug.Print vbTab & "'NewSheet.Range(""B5"") = " & NewSheet.Range("B5").Value & "' and has '" & TypeName(NewSheet.Range("B5").Value) & "' data type"
Debug.Print vbTab & "'colnum = " & colnum & "'" & vbLf
Next
End Sub
输出 2
.Finding for 'Date_var = 20211207' which has 'Double' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 2'
.Finding for 'Date_var = 20211207' which has 'Long' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 2'
.Finding for 'Date_var = 20211207' which has 'String' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 2'
.Finding for 'Date_var = 20211207' which has 'String' data type:
'NewSheet.Range("B5") = 07.12.2021' and has 'Date' data type
'colnum = 2'
旁注:查找搜索文本