EXCEL VBA:循环遍历列和复制

时间:2016-08-26 11:34:22

标签: vba excel-vba excel-2010 excel

在excel中我有四列。第一列中有数字,第二列是空白,第三列也包含数字,第四列包含文本。

我想检查第一列中的每个值,并检查它是否存在于第三列中。如果是,则应将相应第三列旁边的第四列中的值复制到相应第一列旁边的第二列。

我收到错误编译错误。接下来没有For。到目前为止,这是我的代码:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                             bundle:nil];
        UserDashboardViewController *users =
        [storyboard instantiateViewControllerWithIdentifier:@"UserDashboardViewController"];

        [self presentViewController:users
                           animated:YES
                         completion:nil];

2 个答案:

答案 0 :(得分:2)

正如上面的评论中已经指出的那样,您也可以使用VLookUpINDEX/MATCH的组合来完成此操作。但是,如果您希望坚持使用VBA,那么您应该稍微调整一下代码。

Option Explicit

Sub Compare()

Dim ws As Worksheet
Dim i As Long, j As Long
Dim colA As Long, colC As Long

Set ws = ThisWorkbook.Worksheets("Sheet1")
colA = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
colC = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row

'loop through column A
For i = 2 To colA
    'loop through column C
    For j = 2 To colC
        ' If a match is found:
        If ws.Cells(i, 1).Value2 = ws.Cells(j, 3).Value2 Then
            ' Copy column B to Column D as written in your code above
            ws.Cells(j, 4).Value2 = ws.Cells(i, 2).Value2
            ' or copy column D to Column B as written in the question / post
            ws.Cells(i, 2).Value2 = ws.Cells(j, 4).Value2
            'Exit For
        End If
    Next j
Next i

ws.Range("D2:D" & colC).FormulaR1C1 = "=INDEX(R2C2:R" & colA & "C2,MATCH(RC[-1],R2C1:R" & colA & "C1,0))"

End Sub

上述代码将同时执行这两项操作:

  1. VBA方式和
  2. 为您编写INDEX/MATCH公式。
  3. 只需删除您不想要的代码段。

答案 1 :(得分:0)

如果您坚持使用您的代码,请使用此固定版本。虽然没有经过测试,但它应该可以正常工作。

Sub Compare()
Dim LastRowA As Long, LastRowB As Long, i As Long, j As Long

With Worksheets("Sheet1")
    LastRowA = .Range("A" & Rows.Count).End(xlUp).Row
    LastRowC = .Range("C" & Rows.Count).End(xlUp).Row

    For i = 2 To LastRowA

        For j = 2 To LastRowC

                If .Cells(i, 1) = .Cells(j, 3) Then .Cells(i, 2) = .Cells(j, 4): Exit For

        Next j

    Next i

End With

End Sub

如果有任何错误,请在评论部分告诉我。