Excel 我正在为以下场景寻找VBA代码:

Excel 我正在为以下场景寻找VBA代码:,excel,vba,Excel,Vba,我正在为以下场景寻找VBA代码: excel工作表中有四列(A、B、C、D),代码应填充D列 逻辑应该是 如果C2=A2,则用B2中的值填充D2 否则,如果C2=A3,则用B3填充D2,以此类推,直到D2得到正确的值 这些列是包含400个条目的长列表 试试这个: Sub MySub() Dim lastRow As Long, i As Long lastRow = Cells(Rows.Count, 3).End(xlUp).Row For i = 2 To la

我正在为以下场景寻找VBA代码:

excel工作表中有四列(A、B、C、D),代码应填充D列

逻辑应该是

  • 如果C2=A2,则用B2中的值填充D2
  • 否则,如果C2=A3,则用B3填充D2,以此类推,直到D2得到正确的值
这些列是包含400个条目的长列表

试试这个:

Sub MySub()
    Dim lastRow As Long, i As Long
    lastRow = Cells(Rows.Count, 3).End(xlUp).Row

    For i = 2 To lastRow
        If Cells(i, 1).Value = Cells(i, 3).Value Then
            Cells(i, 4).Value = Cells(i, 2).Value
        Else If Cells(i + 1, 1).Value = Cells(i, 3).Value Then
            Cells(i, 4).Value = Cells(i + 1, 2).Value
        End If
    Next
End Sub
这是你需要的吗。它对每个D列执行此操作,而不仅仅是对第二个D列

Sub test()
Dim x As Integer
Dim erow As Integer
'erow takes in the value of the last row number.
erow = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
For x = 1 To erow
    For i = x To erow
        If Cells(x, 3).Value = Cells(i, 1).Value Then
            Cells(i, 2).Select
            Application.CutCopyMode = False
            Selection.Copy
            Cells(x, 4).Select
            ActiveSheet.Paste
            Application.CutCopyMode = False
            i = erow
         End If
    Next i
Next x
End Sub