Macro to Fill new added column with vlookup formula - excel

The macro accesses the last sheet in the workbook (always the same format) and adds a column D, with a header. Until here all is well; the final step is where I get issues.
I want the new column filled with the formula:
=VLOOKUP(C2;'Output'!$A:$B;2;FALSE).
Note that the current sheet is different from where the formula looks (sheet Output).
I have tried various codes that I found here and there... but I cannot manage to make it work correctly right.
Here how my code looks currently:
Sub ColumnInsert()
Dim rws As Long
rws = Cells(Rows.Count, "D").End(xlUp).Row
Sheets(Sheets.Count).Select
Range("D:D").EntireColumn.Insert
Range("D1").Value = "BOX Number"
Range("D2:D" & rws).Formula = "=VLOOKUP(C2;'Output'!$A:$B;2;FALSE)"
End Sub
the last row of code is what does not work... could you please help me?

The problem is in your language settings. If you write your formula in a worksheet you use ";" to separate the variables. In Vba you have to use "," so your formula would be:
"=VLOOKUP(C2,'Output'!$A:$B,2,FALSE)"

Related

How to use VLOOKUP in Excel VBA to find matching cells

I am just starting out with Excel VBA and to be honest I am not that skilled in using normal Excel either.
I've got one sheet that has unique codes in column C, I also have another sheet that has unique codes in column A (except first rows as they've got column labels).
In case this unique code from sheet 1 is also found in the column in sheet 2, I want column J in the sheet1 to have that code value, otherwise, if it cannot be found, I want it to have #N/A.
Normally in Excel I would do this by selecting J2 and entering following function:
=VLOOKUP(C2,Sheet2!A:A,1,False)
Then I'd just double click the corner of the cell to populate all rows.
How do I do it in VBA? I wrote this code hoping it would do something:
Worksheets("Sheet1").Activate
ActiveSheet.Range("J:J").Value = Application.VLookup(C2,Worksheets("Sheet2").Range("A:A"),1,False)
However, this does not work. I just get #N/A for all cells in the J column. Any suggestions what I can do?
The following code will give you what you want. Note that you would only want to put the formula into rows where values actually exist in column C on sheet1.
Option Explicit
Sub InsertVlookup()
Dim LastRow As Long
LastRow = Sheet1.Cells(Rows.Count, 3).End(xlUp).Row
With Sheet1.Range("J2:J" & LastRow)
.FormulaR1C1 = "=VLOOKUP(RC[-7],Sheet2!C[-9],1,FALSE)"
.Value = .Value
End With
End Sub

Countif with reference to different sheet

Hello I will need help with problem I am facing right now and even Google couldn't help me.
I would like to add to field AS2 a COUNTIF formula with source information from different sheet.
This COUNTIF should jump to sheet ee_lpk and then take a range from column A2 down to the end of last used row. and compare that with criteria from field D.
so for AS2 will be comparing with D2 for AS3 with D3.
When I recorded that it showed:
ActiveCell.FormulaR1C1 = COUNTIF(ee_lkp!R[-143]C[-44]:R[217]C[-44],R[-143]C[-41])"
this is working but just in case that there is on ee_lpk page same number or rows what is changing from day to day.
Any help will be much appreciated.
Martin
You need to break this problem down using variables. Try something like this:
sub Answer()
Dim srcRng as Range
Dim srcLength as Long
'First find how many rows on sheet ee_lpk and store it as a variable
srcLength = Sheets("ee_lkp").UsedRange.Rows.Count
'Then use that variable to get your range
Set srcRng = Range(Cells(2,1), Cells(srcLength, 1))
'Or another viable option would be:
'Set srcRng = Range("A2:A" & srcLength)
'Then put that in your Countif formula
ActiveCell.FormulaR1C1 = _
"=COUNTIF(ee_lkp!" & srcRng.Address(True, True, xlR1C1) & ", R[-143]C[-41])
End Sub

Issue with Complex Formula Being Placed Onto Sheet Via VBA and Interacting with Pivot Table

I am having an issue with a formula being placed onto my worksheet via vba. The formula interacts with data on a pivot table. When placed in cell Y8 on the worksheet the following formula functions as desired (non vba):
=IF(OR(L8="(blank)",L8=""),IF((K8-$A$2)/(365/12)<0,0,(K8-$A$2)/(365/12)),IF((L8-$A$2)/(365/12)<0,0,(L8-$A$2)/(365/12)))
The idea is to check if L8 is either null or (blank), if it is then use this formula: IF((K8-$A$2)/(365/12)<0,0,(K8-$A$2)/(365/12)). If L8 has a value (will be a date) then I want to use this slightly differnt formula: IF((L8-$A$2)/(365/12)<0,0,(L8-$A$2)/(365/12))).
Columns L and K are in a pivot table.
I used activecell.formulaR1C1 to translate my on sheet formula to R1C1. The only change I made was adding a set of quotation marks around "(blank)" --> ""(blank)"".
I am still getting a run-time 1004 message on my formula line of vba.
My VBA Code is here:
Sub PerformFormulas()
Dim LastRow As Long
LastRow = Worksheets("Calculator").Range("C" & Rows.Count).End(xlUp).Row
Worksheets("Calculator").Range("Y8:Y" & LastRow - 1).FormulaR1C1 = "=IF(OR(RC[-13]=""(blank)"",RC[-13]=""),IF((RC[-14]-R2C1)/(365/12)<0,0,(RC[-14]-R2C1)/(365/12)),IF((RC[-13]-R2C1)/(365/12)<0,0,(RC[-13]-R2C1)/(365/12)))"
End Sub
I checked that LastRow and Calculator are being recognized correctly and they are (I changed to a simple .select formula and that portion of the code works alright).
Thanks in advance for any help!
You didn't escape the other pair of quotes:
"=IF(OR(RC[-13]=""(blank)"",RC[-13]=""), ...
should be
"=IF(OR(RC[-13]=""(blank)"",RC[-13]=""""), ...

Copy raw data into specific cells of a target sheet

I have two worksheets within the same workbook, namely sheet1 ("rawdata") and sheet2 ("Overview).
I copy downloaded data into sheet1 ("rawdata"). Here the number of rows vary but heading/columns are always the same. After this I need to copy specific cells into another worksheet.
Here are the "rules" I was thinking about:
1) Always copy cells from the rawdata sheet E9, W9, X9 and Y9 into a specific cell in the target sheet. I had something like this (which worked):
Worksheets("overview").Range("X10").Value = Worksheets("rawdata").Range("E9").Value
2) Always copy the value within column E in the lastrow. However, the last row is varying from rawdata to rawdata while the column (E) stays the same. I tried something like this: (not working)
....= Worksheets("rawdata").Range("E1").End(xlDown).Value
3) The script should be linked to the button, when I click the button again to insert the data from the sheet rawdata, the data should be inserted in the next (following) column of worksheet overview.
Assumes column E always has data. Which in this case should be true.
Sorry tried to simplify and broke it.
LastRow_WithDataInColumnE = Worksheets("rawdata").Range("E" & .Rows.Count).End(xlUp).Row
Should be
With Worksheets("rawdata")
LastRow_WithDataInColumnE = .Range("E" & .Rows.Count).End(xlUp).Row
End With
Now .Rows.Count should refer to Worksheets("rawdata")
Worksheets("overview").Range("X10").Value = Worksheets("rawdata").Range("E" & .Rows.Count).End(xlUp).Row.Value
Should be
With Worksheets("rawdata")
Worksheets("overview").Range("X10").Value = .Range("E" & .Rows.Count).End(xlUp).Row.Value
End With
There is a discussion here Error in finding last used cell in VBA. Suggests a better solution for situations where there is no data in Column E or where rows have been deleted.
You could do something like this to get the last data range in column E:
Public Function FindLastColumnECellAvailable()
FindLastColumnECellAvailable = "E" & WorksheetFunction.CountA(Range("E:E"))
End Function
Then you will have this:
At the end just read the cell value:
Range(FindLastColumnECellAvailable).Value
Greetings
Sorry
An apologize "in advance", I just read the date, hope this will help you yet or anyone else, it's my second day

Excel VBA: changing hard coded column to dynamic range to autofill to last row

Hello from an unexperienced vba user.. I'm having trouble with the code for autofill to the last row when trying to use named ranges for the column. Everything seems to work fine when I use a hard coding for the column, in this case Column CW, and what I need is to replace this column CW with a named range so that the macro will still work when adding or deleting columns in the worksheet.
I used the following named ranges:
First_Date: This is the header cell of one of the columns (in this case AP5)
Second_Row: This is the range of columns I want to copy the formulas from (AP7:CW7)
Second_Cell: The cell where I want to start to autofill (AP7)
Last_Column: This is column CW that I want to use in the code. Autofill would be up to this column and down to the last row.
After searching in different threads, I came up with the following code that seems to work fine. How can I change column CW to a named range? Or do I need to change the code?
Dim Lr As Integer
Lr = Range("First_Date").End(xlDown).Row 'Searching last row
Rows(Lr).Insert Shift:=xlDown 'Inserting new row
Range("Second_Row").AutoFill Destination:=Range(Range("Second_Cell"), Range("CW" & Lr))
Can anyone assist me here please?
This will get the job done :-)
Sub RangerFiller()
'The Cell that holds the formula B1
OriginalFormula = Cells(1, 2).Formula
'copies formula down to the last column next to B but use can use another column as
'a counting column....the column that hold the last value
Range("B2:B" & Cells(Rows.Count, "A").End(xlUp).Row).Formula = OriginalFormula
End Sub
Someone gave me the solution:
Change
Range("CW" & Lr)
To
Cells(Lr, Range("Last_Column").Column)
I faced a similar problem because I don't want to hard code the cell reference. I found this solution below to be useful, by using "& ______ &" to replace the cell number that can be calculated using input box or formula.
Eg.
cell1 = last row of column A
Range("CW " & cell1 &" :CW & Lr),
where cell1 = any number that can be added via input box/formula.
Hope this helps!

Resources