簡體   English   中英

Excel VBA。查找范圍異常

[英]Excel VBA .Find Range Anomaly

“在將我的頭發拔了四個小時之后,發現了一個有趣的東西。

如果第一列的寬度對於所使用的字體大小而言太窄,則Excel 2010 VBA似乎在合並的單元格范圍內找不到日期值。 (這類似於Excel VBA無法在隱藏的行/列中找到日期值)。

3種可能的解決方案

  1. 將LookIn參數更改為xlFormulas。
  2. 擴大列,直到宏與LookIn:= xlValues一起使用。
  3. 減小字體大小,直到宏與LookIn:= xlValues一起使用。

重現步驟:

  1. 在A2中插入一個日期(例如7/3)。
  2. 跨4列合並(A2:D2)-這是要查找的日期的字段
  3. 在單元格A4:A35中創建一組順序日期(例如1/3至31/3)。
  4. 跨4列合並(A4:D35)

運行以下代碼:

Sub findDate()
Dim myRange As Range
Dim myDate As Date
Dim myFindDate As Date
Dim myRow As Integer

With ActiveSheet

    Set myRange = .[A2]

    myFindDate = .[A4:D35].Value

    On Error Resume Next

    myRow = myRange.Find( _
        what:=myFindDate, _
        LookIn:=xlValues, _
        LookAt:=xlWhole, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=False, _
        SearchFormat:=False).Row

    On Error GoTo 0

    If myRow <> 0 Then
        MsgBox "The date is in row number = " & myRow
    Else
        MsgBox "Column A too narrow.  Either use LookIn:=xlFormulas, widen Column A or reduce the font size."
    End If

End With

End Sub

請注意,消息框顯示了相關的行號。

現在將A列的寬度減小到2.4,然后再次運行代碼。

注意出現的消息框:Excel VBA不再能夠找到日期!

這是上面解決方案1的代碼:

Sub findDate()
Dim myRange As Range
Dim myDate As Date
Dim myFindDate As Date
Dim myRow As Integer

With ActiveSheet

    Set myRange = .[A2]

    myFindDate = .[A4:D35].Value

    On Error Resume Next

    myRow = myRange.Find( _
        what:=myFindDate, _
        LookIn:=xlFormulas, _
        LookAt:=xlWhole, _
        SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=False, _
        SearchFormat:=False).Row

    On Error GoTo 0

    If myRow <> 0 Then
        MsgBox "The date is in row number = " & myRow
    Else
        MsgBox "Column A too narrow.  Either use LookIn:=xlFormulas, widen Column A or reduce the font size."
    End If

End With

End Sub

(唯一的更改是在LookIn參數中:xlFormulas而不是xlValues)

如果您運行第二行代碼,則消息框將再次顯示行號。

希望這可以減輕別人給我帶來的痛苦!

加里

我按照您的“復制步驟”指示進行操作,您的示例對我不起作用。

我注意到了一些事情。

Dim myDate As Date
Dim myFindDate As Date
Dim myRow As Integer

值可能是日期,但您正在使用范圍。 因此,正確啟動代碼,

 Dim myRange As Range, myFindDate As Range, myRow As Range

然后正確設置范圍。

 Set myRange = [A2]
 Set myFindDate = [A4:D35]
 Set myRow = myFindDate.Find(what:=myRange, lookat:=xlWhole)

通過這種方式使用代碼,列的寬度無關緊要。

完整的代碼。

Sub findDateB()
    Dim myRange As Range, myFindDate As Range, myRow As Range

    Set myRange = [A2]
    Set myFindDate = [A4:D35]
    Set myRow = myFindDate.Find(what:=myRange, lookat:=xlWhole)

    If Not myRow Is Nothing Then
        MsgBox "The date is in row number = " & myRow.Row
    Else: MsgBox "Not Found"
        Exit Sub
    End If

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM