在一列中搜索字符串,并将值添加到同一行中的四个不同单元格

时间:2015-11-17 05:19:19

标签: excel vba excel-vba find

我在Excel VBA中遇到问题编码。我想在所有列f上运行查询以获得一个' mug'的字符串,然后我想将值添加到列H,I,J,K。

Example

我知道它需要一个for循环遍历所有列f以查询“杯子”。之后,我不确定如何将值添加到三个不同的列。

Pseudocoded:

If column f = "mug", then write 5 to column g, 10 to column h, 15 column i

1 个答案:

答案 0 :(得分:0)

Sub test_wordisbarn()
Dim FirstAddress As String, cF As Range

ActiveSheet.Range("F1").Activate
With ActiveSheet.Range("F:F")
    'First, define properly the Find method
    Set cF = .Find(What:="mug", _
                After:=ActiveCell, _
                LookIn:=xlValues, _
                LookAt:=xlPart, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, _
                MatchCase:=False, _
                SearchFormat:=False)

    'If there is a result, keep looking with FindNext method
    If Not cF Is Nothing Then
        FirstAddress = cF.Address
        Do
            'Add your value in other columns
            cF.Offset(0, 1).Value = 5
            cF.Offset(0, 2).Value = 10
            cF.Offset(0, 3).Value = 15

            Set cF = .FindNext(cF)
        'Look until you find again the first result
        Loop While Not cF Is Nothing And cF.Address <> FirstAddress
    End If
End With

End Sub