I'd like to match column A between two worksheets, and if there is a match, data of column B (sheet1) of the corresponding row should be copied to column B (sheet2).
Sheet 1:
COLUMN A-----------------COLUMN B
Company name 1----------Startdate 1
Company name 2----------Startdate 2
Company name 3----------Startdate 3
etc.
Sheet 2:
COLUMN A
Company name 1
Company name 1
Company name 1
Company name 2
Company name 2
Etc.
I need to do this for multiple files which have varying number of rows.
The way I tried it is below, but it ends up only copying data to C3. Anyone know what I'm doing wrong?
Sub Startdatum()
cntcomp = ActiveWorkbook.Worksheets("Component").Range("A2", Worksheets("Component").Range("A2").End(xlDown)).Rows.Count
cntbedrijf = ActiveWorkbook.Worksheets("Bedrijf").Range("A2", Worksheets("Bedrijf").Range("A2").End(xlDown)).Rows.Count
For i = 2 To cntcomp
For j = 2 To cntbedrijf
If ActiveWorkbook.Worksheets("Component").Cells(1, i).Value = ActiveWorkbook.Worksheets("Bedrijf").Cells(1, j).Value Then
ActiveWorkbook.Worksheets("Component").Cells(3, i).Value = ActiveWorkbook.Worksheets("Bedrijf").Cells(2, j).Value
End If
Next j
Next i
End Sub
Try this (revised):
Function Startdatum(cell As Variant, cellrange As range, Optional celltarget As Variant) As String
For Each j In cellrange
If j = cell Then Startdatum = IIf(IsMissing(celltarget), j, celltarget): Exit Function
Next
End Function
Put that into a new module, then you can enter into the first cell =Startdatum(A1,$C$1:$C$7,D1)
A1 is the cell you want to compare.
$C$1:$C$whatever (the $'s maintain the range when you drag it down) is the range of cells you want to compare it with...
D1 is the cell you want to copy if there is a match
Drag down to do the whole range...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.