簡體   English   中英

.Find函數后出現.FindNext失敗(excel vba)

[英].FindNext failing after a .Find function (excel vba)

我正在嘗試使用.Find.FindNext搜索單列數據。 我首先需要找到包含值“Total”的第一個單元格。 我試圖獲得的單元格是“Total”單元格后面包含值“Tech”的第三個單元格。 已知確定細胞(1,1)不含“Tech”或“Total”。

Dim FirstTotal As Range
Dim SearchRng As Range
Dim ResultRng As Range
Set SearchRng = Range("A:A")

Set FirstTotal = SearchRng.Find(What:="Total", After:=Cells(1, 1), SearchDirection:=xlNext)
Set ResultRng = SearchRng.Find(What:="Tech", After:=FirstTotal, SearchDirection:=xlNext)
SearchRng.FindNext().Activate
SearchRng.FindNext().Activate

我運行此代碼的時間大約有50%,我在Set ResultRng =開頭的行上遇到類型不匹配錯誤。 剩下的時間,代碼一直在運行,但結果看起來好像完全忽略了最后兩行代碼。

我懷疑這里的答案非常簡單,但我很擅長excel vba,到目前為止我找到的資源都沒有回答過這個問題。 請幫忙!

如果未找到“Total”,則FirstTotal將為Nothing,當您嘗試在ResultRange Find(第2行)中使用FirstTotal作為“After”參數時,將導致類型不匹配。 這樣可以防止出現錯誤:

Set FirstTotal = SearchRng.Find(What:="Total", After:=Cells(1, 1), SearchDirection:=xlNext)
If Not FirstTotal is Nothing Then
   Set ResultRng = SearchRng.Find(What:="Tech", After:=FirstTotal, SearchDirection:=xlNext)
End If

一般來說,任何依賴的Finds都需要以這種方式對待。

顯然,這里需要某種Else聲明,但我不知道那會是什么。

這會有幫助嗎?

主題 :.Find和.FindNext在Excel VBA中

鏈接http//www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/

從鏈接中提取:

Sub Sample()
    Dim oRange As Range, aCell As Range, bCell As Range
    Dim ws As Worksheet
    Dim ExitLoop As Boolean
    Dim SearchString As String, FoundAt As String
    On Error GoTo Err
    Set ws = Worksheets("Sheet3")
    Set oRange = ws.Columns(1)

    SearchString = "2"
    Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
    If Not aCell Is Nothing Then
        Set bCell = aCell
        FoundAt = aCell.Address
        Do While ExitLoop = False
            Set aCell = oRange.FindNext(After:=aCell)

            If Not aCell Is Nothing Then
                If aCell.Address = bCell.Address Then Exit Do
                FoundAt = FoundAt & ", " & aCell.Address
            Else
                ExitLoop = True
            End If
        Loop
    Else
        MsgBox SearchString & " not Found"
    End If
    MsgBox "The Search String has been found at these locations: " & FoundAt
    Exit Sub
Err:
    MsgBox Err.Description
End Sub

暫無
暫無

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

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