How to get VLOOKUP to select down to the lowest row in VBA? - vba

Looking to automate the insertion of a VLOOKUP formula in a cell.
When recording the macro I instruct it to populate the columns below with the same formula. Works great, however, there is an issue when the table that the VLOOKUP searches through changes (more or less rows).
As it's recorded, the VLOOKUP drops down to the final row in the table (273). However, I want to set it up so that it will go down to the very last row. Meaning that I can run the script on tables of varying numbers of rows.
Selected columns will remain the same.
Range("AJ2").Select
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-20], Previous!R2C2:R273C22,17,FALSE)"

try this:
With Worksheets("Previous")
Range("AJ2").FormulaR1C1 = _
"=VLOOKUP(RC[-20], Previous!R2C2:R" & .Cells(.Rows.Count, 2).End(xlUp).Row & "C22,17,FALSE)"
End With
where:
Range("AJ2")
will implicitly reference the ActiveSheet
.Cells(.Rows.Count, 2).End(xlUp).Row
will reference "Previous" worksheet, being inside a With Worksheets("Previous")- End With block

#nbayly said it, plenty of posts on this. Infact i have provided an answer to this before here:
How to Replace RC Formula Value with Variable
below is slightly modified for a dynamic range, which is what i believe you are looking for
For j = n To 10 Step -1
If Cells(j, 1).Value = "" Then
Cells(j, 1).Formula = "=VLookup(RC20,Previous!R2C2:R273C22,17,FALSE)"
End If
Next j
remember to define j as long and n=sheets("sheetname)".cells(rows.count,1).end(xlup).row
replace 10 in j = n to 10 with the starting row number

Related

Array Formula in vba code with coping the formula down

I work on the code that will calculate Array Formula basing on how many records is in the column N:N that is 11 columns earlier (offset 11). I want to use the formula with array that will use the parallel row from the column N:N and copy down until the last record in column N:N exist. However, for now, formula copies down basing on the first record only instead of taking the row in parallel:
With ThisWorkbook.Sheets("Sheet1")
TargetRow = 4
.Range("N4", .Cells(Rows.Count, "N").End(xlUp)).Offset(0, 11).FormulaArray = "=IFERROR(Name&INDEX(Names_Area,MATCH(RC[-11],Name&Name_Origin,0),2),"""")"
End With
I heard about fill down function or something alike but I am not sure how to insert it here.
How can I fix it so when the formula copies down into rows it takes the row in parallel and not all the time N4 (that is the first row of records).
I will appreciate any help.
I also want to mention that any other formula without array works and copies formula down basing on the rows in column N:N that are in paralell.
Try with .Autofill. something like:
With ThisWorkbook.Sheets("Sheet1")
TargetRow = 4
.Range("N4").FormulaArray = "=IFERROR(Name&INDEX(Names_Area,MATCH(RC[-11],Name&Name_Origin,0),2),"""")"
.Range("N4").AutoFill .Range("N4:N12")
End With
I have used an example end point of N12 for the autofill which you can adjust.
Though note you are actually going to column Y with:
.Range("N4", .Cells(Rows.Count, "N").End(xlUp)).Offset(0, 11)
So you may want to ensure you autofill and populate formula in the actual column you want to fill.
Maybe something like:
.Range("N4").Offset(0, 11).FormulaArray =
Reference:
https://www.mrexcel.com/forum/excel-questions/500971-how-copy-array-formula-down-vba-macro.html
you could also use
With ThisWorkbook.Sheets("Sheet1")
With .Range("N4", .Cells(Rows.Count, "N").End(xlUp)).Offset(0, 11)
.Cells(1, 1).FormulaArray = "=IFERROR(Name&INDEX(Names_Area,MATCH(RC[-11],Name&Name_Origin,0),2),"""")"
.Formula = .Cells(1, 1).Formula
End With
End With

r1c1 formula not working

I am trying to rank values using column J and tie breaker in column K with the result populating in column N. Column J & K are values.
Somehow it only generates one value wherever my cell is pointed at, which means if I run the vba codes at cell C19, it will just populate value 1 in C19, not from N6 where I want the results to be.
Here are my codes,
Sub test()
Dim LR1 As Long
LR1 = Range("J" & Rows.Count).End(xlUp).Row
With Range("N6:N" & LR1)
ActiveCell.FormulaR1C1 = "=1+SUMPRODUCT(--(R6C10:R33C10<RC[-4]))+SUMPRODUCT(--(R6C11:R33C11<RC[-3]),--(R6C10:R33C10=RC[-4]))"
End With
End Sub
I am not sure what went wrong. I tried to do it manually using the excel formula and its working fine but not my vba codes.
ActiveCell is your issue.
Change
ActiveCell.FormulaR1C1 = "=1+SUMPRODUCT(--(R6C10:R33C10<RC[-4]))+SUMPRODUCT(--(R6C11:R33C11<RC[-3]),--(R6C10:R33C10=RC[-4]))"
To .FormulaR1C1 = "=1+SUMPRODUCT(--(R6C10:R33C10<RC[-4]))+SUMPRODUCT(--(R6C11:R33C11<RC[-3]),--(R6C10:R33C10=RC[-4]))"
Remove that and it should do what you want.
You will want to fully qualify your Range references that way they aren't depending on the ActiveSheet. This will provide you with consistent behavior and results.

Loop through columns and copy and paste cells A to B

I am working on a simple code but i have not able to crack it. i want the macro to run and pick up a value (2), and copy and paste the cells A to C , into sheet 2. The code below does copy the Cells A-B and pastes. I failing on the loop . I want it to loop from 1st row to last row. please.
Sub Tier_2()
With Sheets("Sheet1")
.Range(.Cells(1, 1), .Cells(3, 3)).Copy Sheets("Sheet2").Cells(1, 1)
End With
End Sub
This isn't for your specific situation, but the concept is what you are looking for. You should be able to do some research with what I'm showing you and figure it out.
lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row 'gets last row of Source sheet
For x = 1 to lastRow
Sheets("Sheet2").Cells(x, 1) = Sheets("Sheet1").Cells(x, 1) 'copy data from Sheet1 to Sheet2 row x
Next x 'loop and add one to x
You can use variables for either the row or column numbers in either the source or target sheets. You can insert another loop inside the first one. I'm not sure of what you are looking for, but your question didn't seem to have a loop in it at all.
If that doesn't get you going in the right direction try "Do While Loop" in a search.
EDIT: Updated the formula to better reflect idea.

How to delete duplicates from each row but not delete the whole column

For context, I have a worksheet with job titles in Column A, then in columns B onwards, it has the name of a person who does that job. However, as it is populated from multiple projects, some job titles have duplicates in the row, where the same person does the same job on different projects. What I need to do is delete the duplicates from each row. All solutions I have tried have given me errors.
Can anyone help?
The data gets to its current form using VBA, copying it from another sheet, so if it could be integrated into the copying, it wouldn't be a problem.
update:
So in an earlier part of the macro, I have to do this, but for a single column. This works:
For np = lastRow To 1 Step -1
If Application.WorksheetFunction.CountIf(Range("D1:D" & np), Range("D" & np).Text) > 1 Then
Range("D" & np).ClearContents
End If
Next np
However, when I tried to add another loop outside this one, and change the D1:D to a variable, I fall down.
And what I want it to do is go from the top 4 rows in the picture, to the bottom 4. I have 78 jobs, and some of them have 20 people including the duplicates http://picture.ms/images/2013/09/18/Capture1.png:
if you want to use two loops, how about something like this
Sub RemoveDuplicates()
Dim i As Integer
Dim j As Integer
For i = 1 To Range("A65536").End(xlUp).Row
For j = i + 1 To Range("A65536").End(xlUp).Row
If Cells(i, 1) = Cells(j, 1) Then
If i <> j Then
'just clear the duplicate cell...
Cells(j, 1).ClearContents
'or to delete the entire row if a duplicate is found...
'Cells(j, 1).EntireRow.Delete
End If
End If
Next
Next
End Sub
NB - I've used Range("A65536").End(xlUp).Row to get the last row of data in column A, in Excel2007 and above there more rows on a worksheet, but it sounds like your data is much less than this anyway

I need a VBA code to count the number rows, which varies from ss to ss, return that number and copy and paste that row and all other columns

I have vba question I have been trying to find the answer for for a long time. I have numerous spreadsheets from numerous clients that I run macro's on, I'm new to coding and have been able to mostly figure out what I need to do. My clients send us data monthly and every month the number of rows change. The columns don't change but the amount of data does. My previous macro's I have just chosen the entire column to copy and paste onto our companies template. This worked fine for must things but has created some really long code and macros take a long time. I would like to write a code that counts how many rows are in a certain column and then from there copies and pastes that however many rows it counted in each column. Only a few columns contain data in every row, so I need it to count the rows in one specific column and apply to that every column. Any help would be appreciated.
Thanks
Tony
Hi Guys,
Still having issues with this, below I pasted the code I'm using if anyone can see why it won't run please help.
Windows("mmuworking2.xlsx").Activate
Workbooks.Open Filename:= _
"C:\Users\I53014\Desktop\QC DOCS\Sample_Data_Import_Template.xlsx"
Windows("mmuworking2.xlsx").Activate
Dim COL As Integer
COL = Range("A:DB").Columns.Select
**Range(Cells(2, COL), Cells(Range("E" & Rows.Count).End(xlUp).Row, COL)).Copy Destination:=Windows("Sample_Data_Import_Template.xlsx").Range("A2")**
Range("A2").Paste
Range("A5000").Formula = "='C:\Users\I53014\Desktop\[Import_Creator.xlsm]sheet1'!$B$2"
ActiveWorkbook.SaveAs Filename:="Range (A5000)", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
I bolded where it keeps stopping.
This should give you the last row containing data:
ActiveSheet.UsedRange.Rows.Count
This will give you the last row in a specific column:
Range("B" & Rows.Count).End(xlUp).Row
here is an example of how I can copy every row in the first three columns of a worksheet
Sub Example()
Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, 3)).Copy Destination:=Sheet2.Range("A1")
End Sub
You have to be careful as there are some caveats to both methods.
ActiveSheet.UsedRange may include cells that do not have any data if the cells were not cleaned up properly.
Range("A" & Rows.Count).End(xlUp).Row will only return the number of rows in the specified column.
Rows(Rows.Count).End(xlUp).Row will only return the number of rows in the first column.
Edit Added an example
Edit2 Changed the example to be a bit more clear
For this example lets say we have this data
You could copy any other column down to the number of rows in column A using this method:
Sub Example()
Dim Col as Integer
Col = Columns("C:C").Column
'This would copy all data from C1 to C5
'Cells(1, Col) = Cell C1, because C1 is row 1 column 3
Range(Cells(1, Col), Cells(Range("A" & Rows.Count).End(xlUp).Row, Col)).Copy Destination:=Sheet2.Range("A1")
End Sub
The end result would be this: