如何遍历各种单元格并在另一个工作表中返回值

时间:2019-04-19 07:23:04

标签: excel vba

工作表“ Google地图”中的单元格C8和C9具有上车点和下车点。计算距离并显示在C18中。工作表“ Sheet 2”还具有带有接点的A列和带有相应下拉菜单的Row 1。

我想编写VBA代码,该代码将循环遍历,并将“第2页”中的每个拾取和下注引用到“ Google地图”,然后返回它们各自的距离。

Sub Distance()
'
' Distance Macro
' To populate distance
'
' Keyboard Shortcut: Ctrl+Shift+D
'
    Sheets("Google maps").Select
    Range("C8").Select
    ActiveCell.FormulaR1C1 = "=Sheet2!R[-6]C[-2]"
    Range("C9").Select
    ActiveCell.FormulaR1C1 = "=Sheet2!R[-8]C[-1]"
    Sheets("Sheet2").Select
    Range("B2").Select
    ActiveCell.FormulaR1C1 = "='Google maps'!R[16]C[1]"
    Range("B3").Select
End Sub

1 个答案:

答案 0 :(得分:0)

这应该做您所需要的。使用前,请确保在电子表格的副本上对此进行测试。

Sub double_lookup()

    PickUp = ThisWorkbook.Sheets(1).Range("C8").Value
    dropoff = ThisWorkbook.Sheets(1).Range("C9").Value
    distance = ThisWorkbook.Sheets(1).Range("C18").Value

    lastrow = ThisWorkbook.Sheets(2).Cells(ThisWorkbook.Sheets(2).Rows.Count, "A").End(xlUp).Row
    Set Rng = ThisWorkbook.Sheets(2).Range("A1:A" & lastrow)

    xindex = ""
    Count = 1
    For Each cell In Rng
        If cell.Value = PickUp Then
            xindex = Count
            Exit For
        End If

        Count = Count + 1
    Next cell

    yindex = ""
    lastcol = ThisWorkbook.Sheets(2).Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
    For i = 1 To lastcol
        If ThisWorkbook.Sheets(2).Cells(1, i).Value = dropoff Then
            yindex = i
            Exit For
        End If

    Next i

    If xindex = "" Or yindex = "" Then
        MsgBox ("pickup or dropoff not found in sheet 2")
    Else
        ThisWorkbook.Sheets(2).Cells(xindex, yindex).Value = distance
    End If

End Sub