VB code for VLOOKUP - vba

I'm completely new to VBA. I tried recording a macro of using VLOOKUP function in my spreadsheet, but turns out VLOOKUP recorded like that does not work.
I have a working spreadsheet and I am comparing values in the column "Material" with a different workbook that is like a database for all the materials and their respective programs. The program the material number matches to in the database will be recorded under column "Program" in the working spreadsheet. I use VLOOKUP to do this, but I am having a hard time coming up with a macro for it.
As suggested, I did the following:
ActiveCell.FormulaR1C1 = "'Program"
Range("K41").Select
ActiveCell.Formula = "VLOOKUP(D41,"'C:\Users\Username\Desktop[Database.xlsx]Sheet1!R1C1:R152289C4,4,FALSE)"
But it still does not populate the "Program" column. What am I doing wrong?

The exact line for vlookups can be done in two ways;
1) This does a vlookup within the coding environment, it's more difficult to make it dynamic
application.worksheetfunction.vlookup(worksheets("Material").range("A2"), worksheets("Program").range("A1:F10"),4,0)
2) Make the formula in the cell the vlookup
range("c2").select
activecell.formula = "=vlookup(A1,Material!A1:F10,4,0)"
and then use the environment to fill in.
Maudise

Big thank you to all who took the time to address my question. I took suggestions, played around with the formula, and this is what I got:
=VLOOKUP($D41,'C:\Users\Username\Desktop[Database.xlsx]Sheet 1'!$A$1:$B$40973,2,FALSE)
Does exactly what I wanted it to do! Thanks again!

Related

Vba email generator, subject from excel spreadsheet

I have a vba code that generates an email. I would like the subject to be the data from the first and last cells in my list. The thing is, my list isnt of a set length, sometimes it contains 5 pieces of data sometimes 8 etc. How do i tell vba to pick the first and last cell no matter the length of the list?
thanks
For me, best practice is to just have cells on your sheet that calculate the first and last row (different ways you can do that), then give those cells a range name such as FirstRow and LastRow. In your vba then you refer to these cells to make your code dynamic.
e.g:
firstRow = Range("FirstRow)
lastRow = Range("lastRow")
test = range(cells(firstRow,lastRow))
-- Note I have not written VBA in many many years so am writing the above from memory so it may be not be exact.
Of course you can do it all entirely in VBA using the xlDown method mentioned previously but I prefer the transparency of it being on the main page so that easily spot if something breaks.
Range("A1").End(xlDown).Value
Where the cell is where you want to start and the End part moves all the way to the end

Excel formula within VBA

I have quite a few cells that contain formula, then with VBA the outcome of this formula is the value for a variable, like so:
On sheet in cell AS4:
=SUMPRODUCT(MAX((ROW($AE$4:$AE$997))*($AE$4:$AE$997<>"")))
and then in my VBA:
numRows = ws.Range("AS4").Value
However this is starting to get hard to keep track of which cell is feeding which variable, avoiding overwriting those cells on the sheet by accident, etc.
I need to be able to perform this calculation within VBA if I can, removing the need to have "calculation cells" on my sheet.
I have discovered there is a way to use formula with WorksheetFunction, but only found simple examples of this and cannot adapt it to my situation above.
numRows = WorksheetFunction.SumProduct(MAX((ROW($AE$4:$AE$997))*($AE$4:$AE$997<>"")))
Is not going to work...
Is there a way to do this, or am I better scrapping the idea of using formula and using a pure VBA method?
With help from SJR this was the answer:
numRows = [=SUMPRODUCT(MAX((ROW(Weights!$AE$4:$AE$997))*(Weights!$AE$4:$AE$997<>"""")))]
A bit more research taught me that evaluate(" ") can be just replaced with square brackets [ and ]. Although, if I had variables in the mix of this formula or the formula wasn't constant then I would have to use Evaluate.
I also needed to add the sheet name to the formula as this formula was no longer functioning within the sheet and AE4:AE997 was no longer referring to the correct sheet.
Doubling up on quotes is also necessary as it is code and sees " differently to a formula on the sheet

Is there a way to use VBA for Excel to output a formula to a specific cell in an Excel worksheet?

I am fairly new at programming. I feel like this should be a simple fix but I cannot find anything that works. I am trying to use a Select Case structure to write a different formula to a cell depending on the selected case. If I type:
Sheet1.Range("g10").Value = "=IF(SUM(F10)>0,SUM((F10-15)),"")"
I get an error:
Run-time error '1004'
Application-defined or object-defined error.
I can get it to work if I include spaces like so:
Sheet1.Range("g10").Value = " =IF(SUM(F10)>0,SUM((F10-15)),"") "
but then Excel puts it into the cell like text, not as a formula (it doesn't do anything).
I have tried a few different methods but have run into the same issue. Is it possible to do this?
I apologize if this has been asked and answered, but I wasn't able to find anyone referencing this specific problem.
You don't need to sum a single cell ie SUM(F10) Also SUM((F10-15)) is the same as F10-15.
Try this: Sheet1.Range("g10").Formula = "=IF(F10>0,F10-15,"""")" Also note, you needed to double the double quotes towards the end.
Note, you can do this on a range too like this:
Sheet1.Range("g10:g20").Formula = "=IF(F10>0,F10-15,"""")" and it is smart enough to increment the references for you for the 10 cells.
Wrong property. You need .formula not .value
worksheets("sheet1").range("g10").formula = "=IF(SUM(F10)>0,SUM((F10-15)),"")"
You should be able to type out the formula and then turn on the Macro Recorder and double-click on the cell with the forums, then turn off the Macro recorder and examine your code. That should give you what you want.

Find/replace conditionally formatted cells

I've been using a conditional format formula =OR(B2=B1,B2=B3) to highlight consecutive duplicates. I then use format painter to copy the formula to all columns in my excel table.
I have set up a button that will, amongst other things, copy a workbook into a new workbook. I now want to include the above formula in this macro. My final objective is to replace all of the cells found with this formula with an asterisk (*).
I first tried to just pop the formula into the macro as a starting point -
For Each sh In Destwb.Worksheets
With sh.UsedRange.FormatConditions _
.Add(Type:=xlExpression, Formula1:="=OR(B2=B1,B2=B3)")
.Interior.Color = RGB(198, 239, 206)
End With
Next sh
But this just makes a mess of seemingly randomly highlighted cells. I'm not sure where I've gone wrong. Even column B highlights are all wrong. Could the header in B1 affect this? It doesn't when I use the CF normally. How can I expand the CF into all columns uniquely?
Finally, how do I go about working a replacement of formatted cells into this formula? Or is there a quicker/easier way to meet this end-goal?
I didn't realise I could add custom text in that way. That's moved me a good couple of steps forward.
Taking Balinti's suggestion into consideration I've tried a workaround. I was making a couple of assumptions that turned out to be wrong. I have been able to enter the CF into the Array of data that I have in my original workbook. It's not as simple as putting it into a table, but by manually selecting the range in each column and inputting the CF I have made it work.
I also wasn't sure if the formatting would carry through to the new worksheet as I have used the Paste Special command to convert the array formula to values in the new sheet. It does, however, carry the formatting across which is very handy.
It's not the perfect solution for me but it appears to be working so far. I still need to test what happens when I change the date and get updated data. It would still be interesting to know if I can move this formatting into my macro though. Any tips?

Blank Fields Copied as #N/A

I am working with an Excel 2003 VBA script that copies the content from worksheets in an external Excel file to worksheets in our own:
ThisWorkbook.Sheets(strTarget).UsedRange.Value = Workbooks(strFile).Sheets(strSource).UsedRange.Value
In a large number of blank cells, this function is posting #N/A instead of the blank values, which causes errors further down in the VBA code. This only occurs on some sheets, while others copy over just fine, sometimes by adding these values in extra rows and other times in extra columns. I have attempted to clear the error with IsNA to no avail:
If (IsNA(Workbooks(strFile).Sheets(strSource).UsedRange.Value)) Then
ThisWorkbook.Sheets(strTarget).UsedRange.Value = ""
Else: ThisWorkbook.Sheets(strTarget).UsedRange.Value = Workbooks(strFile).Sheets(strSource).UsedRange.Value
Is there a simple way to remove these #N/A values during the copy or even clear them after the fact?
Any other advise on how to handle this issue would also be greatly appreicated, as I'm not a VBA dev myself, but simply the lucky soul who got to pick this up when the only person with Excel and VBA experience left our team. Thanks in advance!
The problem comes when the ranges aren't the same size. You should resize appropriately:
With Workbooks(strFile).Sheets(strSource).UsedRange
ThisWorkbook.Sheets(strTarget).UsedRange.Resize(.Rows.count, .Columns.count).Value = .Value
End With
It's probably safer to clear the target sheet first using:
ThisWorkbook.Sheets(strTarget).UsedRange.ClearContents