簡體   English   中英

搜索具有特定文本的所有單元格的范圍並將所有相鄰單元格的值更改為 0

[英]Search range for all cells with specific text and change the value of all adjacent cell to 0

尋求幫助以實現搜索一系列單元格 E9:E 與所有包含“住宿和運輸”的單元格並將與它們相鄰的單元格的值更改為 0. ,我無法在網上獲得任何類似主題的內容,我m VBA 編碼不太好,盡管我能夠理解代碼將在結果中提供什么。

我有一個帶有以下代碼的 Commandbutton1:

Sub CommandButton1_click()

Dim blanks As Excel.Range

Set blanks = Range("F9:F" & Cells(Rows.Count, 5).End(xlUp).Row).SpecialCells(xlCellTypeBlanks)

blanks.Value = blanks.Offset(0, -1).Value

End Sub

此外,我有一個命令按鈕,它將 select 僅非空白單元格。 我需要上面的結果,因為如果下面的代碼從 E:F 列中選擇非空白單元格,它將不會選擇與包含“住宿和運輸”的單元格相鄰的單元格,因為它們是空白單元格,它將返回錯誤“運行時錯誤'1004'此操作不適用於多項選擇”。

下面的代碼與 [Go to Special => Constants] 的作用相同

Sub SelectNonBlankCells()

Dim rng As Range
Dim OutRng As Range
Dim InputRng As Range
Dim xTitle As String


On Error Resume Next

xTitle = Application.ActiveWindow.RangeSelection.Address

Set InputRng = Range("E8:F500")

ActiveWindow.ScrollRow = 1

For Each rng In InputRng

If Not rng.Value = "" Then

If OutRng Is Nothing Then

Set OutRng = rng

Else

Set OutRng = Application.Union(OutRng, rng)

End If

End If

Next

If Not (OutRng Is Nothing) Then

OutRng.Select

End If

End Sub

如果您的目標是編輯與某些單元格相鄰的單元格,也許您可以嘗試另一種方法。 以下代碼基於Range.Find function 幫助文件中的示例:

Sub DoSomething()

    Dim sh As Worksheet
    Set sh = ActiveSheet
    
    Dim checkRange As Range
    Set checkRange = sh.Range("E8:F500") ' your intended range to search
    
    Dim foundRange As Range
    Set foundRange = checkRange.Find("Accommodation & Transportation")
    
    Dim firstAddr As String
    
    If Not foundRange Is Nothing Then
    
        firstAddr = foundRange.Address
        Do
        
            ' use foundRange to access adjacent cells with foundRange.Offset(row, col)
            '
            '
            foundRange.Offset(0, 1) = "all good"
            
            Set foundRange = checkRange.FindNext(foundRange)
            
        Loop While Not foundRange Is Nothing And foundRange.Address <> firstAddr
    End If

End Sub

甚至更好的是,您可以添加一些參數以使其更可重用:

Sub Main()

    DoSomething "Accommodation & Transportation", ActiveSheet.Range("E8:F500")

End Sub


Sub DoSomething(ByVal findWhat As String, ByVal searchWhere As Range)

    Dim foundRange As Range
    Set foundRange = searchWhere.Find(findWhat)
    
    Dim firstAddr As String
    
    If Not foundRange Is Nothing Then
    
        firstAddr = foundRange.Address
        Do
        
            ' use foundRange to access adjacent cells with foundRange.Offset(row, col)
            '
            '
            foundRange.Offset(0, 1) = "all good"
            
            Set foundRange = searchWhere.FindNext(foundRange)
            
        Loop While Not foundRange Is Nothing And foundRange.Address <> firstAddr
    End If

End Sub

暫無
暫無

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

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