循环行和列中的VBA vlookup

时间:2015-10-20 09:48:04

标签: excel vba excel-vba loops lookup

对不起,我想询问有关行和列的循环使用vlookup。这是我的代码,但没有用。你能帮忙纠正这段代码吗?感谢。

Private Sub CommandButton1_Click()
   Dim ws As Worksheet
   Dim i As Integer
   Dim j As Integer

Set ws = ThisWorkbook.Sheets("GROWTH PERUSAHAAN")

With ws
    For j = 3 To 100
        For i = 2 To 600
            If Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets("GROWTH PERUSAHAAN").Cells(i, 1), ThisWorkbook.Sheets("INPUT KUANTITATIF").Range("A:AC"), j + 3, 0) = "" Then
            ThisWorkbook.Sheets("GROWTH PERUSAHAAN").Cells(i, j) = 0

            Else
            ThisWorkbook.Sheets("GROWTH PERUSAHAAN").Cells(i, j) = (Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets("GROWTH PERUSAHAAN").Cells(i, 1), ThisWorkbook.Sheets("INPUT KUANTITATIF").Range("A:AC"), j + 4, 0) / Application.WorksheetFunction.VLookup(ThisWorkbook.Sheets("GROWTH PERUSAHAAN").Cells(i, 1), ActiveWorkbook.Sheets("INPUT KUANTITATIF").Range("A:AC"), j + 3, 0)) - 1
            End If
        Next i
    Next j
End With

End Sub

2 个答案:

答案 0 :(得分:0)

这应该更有效:

Private Sub CommandButton1_Click()
    Dim ws                    As Worksheet
    Dim wsTable               As Worksheet
    Dim i                     As Long
    Dim j                     As Long
    Dim vMatch

    Set ws = ThisWorkbook.Sheets("GROWTH PERUSAHAAN")
    Set wsTable = ThisWorkbook.Sheets("INPUT KUANTITATIF")

    With ws
        For i = 2 To 600

            vMatch = Application.Match(ws.Cells(i, 1), wsTable.Range("A:A"), 0)
            ' if lookup value isn't found, skip
            If Not IsError(vMatch) Then
                For j = 3 To 100

                    If wsTable.Cells(vMatch, j + 3).Value2 = "" Then
                        ws.Cells(i, j).Value2 = 0

                    Else
                        ws.Cells(i, j).Value2 = (wsTable.Cells(vMatch, j + 4).Value2 / wsTable.Cells(vMatch, j + 3).Value2) - 1
                    End If
                Next j
            End If
        Next i
    End With

End Sub

答案 1 :(得分:0)

请在您的代码中使用“on next resume next”。请设置工作表并设置范围以便于理解

Private Sub CommandButton1_Click()
   Dim ws As Worksheet
   Dim i As Integer
   Dim j As Integer

Set ws = ThisWorkbook.Sheets("GROWTH PERUSAHAAN")
Set ws1 = ThisWorkbook.Sheets("INPUT KUANTITATIF")


With ws
    For j = 3 To 100
        For i = 2 To 600

        On Error Resume Next



            If Application.WorksheetFunction.VLookup(ws.Cells(i, 1), ws1.Range("A:AC"), j + 3, 0) = "" Then
            ws.Cells(i, j) = 0

            Else


            ws.Cells(i, j) = (Application.WorksheetFunction.VLookup(ws.Cells(i, 1), ws1.Range("A:AC"), j + 4, 0) / Application.WorksheetFunction.VLookup(ws.Cells(i, 1), ws1.Range("A:AC"), j + 3, 0)) - 1


            End If


        Next i
    Next j
End With

End Sub