Excel vba - if something copy to one column, else copy to other

beruf3

New Member
Joined
Nov 20, 2015
Messages
43
I have a list of codes in "C" column of Sheet2, and
if the code begins with "xxx" I need to copy value from "D" column of Sheet2
to "A" column of Sheet1,
otherwise to "B" column of Sheet1.

Here's my code.
It's simple, but it works.

Code:
Set ws1 = Sheets("Sheet2")
Set ws2 = Sheets("Sheet1")

FinalRow = ws1.Cells(Rows.Count, "C").End(xlUp).Row

For i = 1 To FinalRow
    If Left(ws1.Range("c" & i).Value, 3) = "xxx" Then
    k = k + 1
    ws2.Range("A" & k).Value = ws1.Range("D" & i).Value
    Else
    j = j + 1
    ws2.Range("B" & j).Value = ws1.Range("D" & i).Value
    End If
Next

Because I have large list of data, is it possible
to it more effectively.
 

Excel Facts

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.
Try this:
Code:
Sub a1014583a()
'https://www.mrexcel.com/forum/excel-questions/1014583-excel-visual-basic-applications-if-something-copy-one-column-else-copy-other.html
Dim i As Long, j As Long, k As Long, finalrow As Long
Set ws1 = Sheets("Sheet2")
Set ws2 = Sheets("Sheet1")

finalrow = ws1.Cells(Rows.count, "C").End(xlUp).row
vc = ws1.Range(ws1.Cells(1, "C"), ws1.Cells(finalrow, "D"))
ReDim va(1 To UBound(vc, 1), 1 To 1)
ReDim vb(1 To UBound(vc, 1), 1 To 1)

For i = 1 To finalrow
    If Left(vc(i, 1), 3) = "xxx" Then
    k = k + 1
    va(k, 1) = vc(i, 2)
    Else
    j = j + 1
    vb(j, 1) = vc(i, 2)
    End If
Next

ws2.Range("A1").Resize(k, 1) = va
ws2.Range("B1").Resize(j, 1) = vb
End Sub
 
Upvote 0
You're welcome & thanks for replying
 
Upvote 0

Forum statistics

Threads
1,214,649
Messages
6,120,731
Members
448,987
Latest member
marion_davis

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top