Hello Excel experts,
I am new to excel VBA, I have a query using multiple IF statement and copying the result on another sheet, I tried Vlookup also, however nothing worked because there are multiple columns in 2nd sheet with the same name and different ColumnD, it looks code checks the first matching and then jumps to another one. I am copying some data here for better understanding. if any expert help me fixing this code I would really appreciate, Thanks in advance for your help!
Sheet 1, where I want to copy the required data based on certain conditions,
ColumnA ColumnB
A
B
C
D
E
Sheet 2, where the data is residing
ColumnA ColumnB ColumnC ColumnD
A Toyota Corrola D
B Mitsubishi Lancer B
C Honda Accord D
M Honda City D
Blank Cell
D Dodge Caravan A
D Toyota Camry B
D Suzuki Swift D
E Nissan XYZ D
My code is as follows,
Private Sub CommandButton1_Click()
Dim i As Long
Dim Lastrow As Long
Set Rng = Sheets("sheet2").Range("A1:D50")
Lastrow = 20
For i = 2 To lastrow
On Error Resume Next
If Sheets("sheet1").Cells(i, 1) <> "" And Sheets("sheet2").Cells(i, 1) <> "" Then
If Sheets("sheet2").Cells(i, 4).Value = "D" Then
If Sheets("sheet1").Cells(i, 1).Value = Sheets("sheet2").Cells(i, 1).Value Then
Sheets("sheet1").Cells(i, 2) = Sheets("sheet2").Cells(i, 2).Value
End If
End If
End If
Next i
End Sub
I am new to excel VBA, I have a query using multiple IF statement and copying the result on another sheet, I tried Vlookup also, however nothing worked because there are multiple columns in 2nd sheet with the same name and different ColumnD, it looks code checks the first matching and then jumps to another one. I am copying some data here for better understanding. if any expert help me fixing this code I would really appreciate, Thanks in advance for your help!
Sheet 1, where I want to copy the required data based on certain conditions,
ColumnA ColumnB
A
B
C
D
E
Sheet 2, where the data is residing
ColumnA ColumnB ColumnC ColumnD
A Toyota Corrola D
B Mitsubishi Lancer B
C Honda Accord D
M Honda City D
Blank Cell
D Dodge Caravan A
D Toyota Camry B
D Suzuki Swift D
E Nissan XYZ D
My code is as follows,
Private Sub CommandButton1_Click()
Dim i As Long
Dim Lastrow As Long
Set Rng = Sheets("sheet2").Range("A1:D50")
Lastrow = 20
For i = 2 To lastrow
On Error Resume Next
If Sheets("sheet1").Cells(i, 1) <> "" And Sheets("sheet2").Cells(i, 1) <> "" Then
If Sheets("sheet2").Cells(i, 4).Value = "D" Then
If Sheets("sheet1").Cells(i, 1).Value = Sheets("sheet2").Cells(i, 1).Value Then
Sheets("sheet1").Cells(i, 2) = Sheets("sheet2").Cells(i, 2).Value
End If
End If
End If
Next i
End Sub