在Excel中使用VBA,如何循环遍历行并设置单元格值?

时间:2013-01-25 21:56:41

标签: excel vba excel-vba

我正在尝试自学一些VBA。我有一个包含2个工作表的工作簿,Sheet1和Sheet2。我在下面找到了这个代码并修改它以适合我。获取Sheet1!B1的值,在Sheet2!K:K中查找它,并将Sheet1!D1设置为Sheet2的E(K - 6)列中的单元格值。

如何循环显示B1:B100并设置D1:D100?

Sub Looping()
    Dim rng1 As Range
    Dim strSearch As String
    strSearch = Range("B1").Value
    Set rng1 = Worksheets("Sheet2").Range("K:K").Find(strSearch, , xlValues, xlWhole)
    If Not rng1 Is Nothing Then
        Range("D1").Value = rng1.Offset(0, -6)
    Else
        MsgBox strSearch & " not found"
    End If
End Sub

谢谢!

1 个答案:

答案 0 :(得分:1)

首先,您不需要针对该问题的VBA解决方案。只需将此公式放入Sheet1!D1:D100:

=IFERROR(INDEX(Sheet2!$E:E$,MATCH(B1,Sheet2!$K:$K,0))),"Not found")

如果您想使用VBA执行此操作,以下是循环中的代码:

Sub Looping()
    Dim rngTarget As Range
    Dim rngSearched as Range

    For Each rngTarget in Sheets("Sheet1").Range("D1:D100")
        Set rngSearched = Sheets("Sheet2").Range("K:K").Find( _
            rngTarget.Offset(, -2).Value, , xlValues, xlWhole)    
        If rngSearch Is Nothing Then
            rngTarget.Value = "not found"
        Else
            rngTarget.Value = rngSearch.Offset(, -6)
        End If
    Next rngTarget
End Sub

或者,结合两种方法:

Sub FillDirectly
    With Sheets("Sheet1").Range("D1:D100")
        .Formula="=IFERROR(INDEX(Sheet2!$E:E$,MATCH(B1,Sheet2!$K:$K,0))),""Not found"")"
        .Calculate
        .Value = .Value 'Creates a value copy
    End With
End Sub