IF statement including VLOOKUP - excel

Looking for a way to do an IF cell says (this) then VLOOKUP here, IF cell says (thiselse) then VLOOKUP different area.
Might be a super obvious way to do this, so far have this:
Pretty simple but not working
Sub categoryVLOOKUP()
'IF col D says STAR then enter VLOOKUP formula into column K
'IF col D says SUN then enter other VLOOKUP formula into column K
Dim lRow As Long, lCol As Long
Dim lRow2 As Long
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("STARSUN")
For lRow = 2 To LastRow
If sht.Cells(lRow, 4) = "SUN" Then
sht.Cells(lRow, 10).Formula = _
"=VLOOKUP(A3&G3,OF_MOON!A:D, 4,0)"
Else
End If
If sht.Cells(lRow, 4) = "STAR" Then
sht.Cells(lRow, 10).Formula = _
"=VLOOKUP(A3&G3,OFWORLD!A:D, 4,0)"
Else
End If
Next lRow
End Sub

If it is getting the formula for multiple cells that is the struggle, I would recommend R1C1 formatting:
Sub categoryVLOOKUP()
'IF col D says STAR then enter VLOOKUP formula into column K
'IF col D says SUN then enter other VLOOKUP formula into column K
Dim lRow As Long, lCol As Long
Dim lRow2 As Long
Dim sht As Worksheet
Dim LastRow as long
LastRow = Cells(Rows.Count, "D").End(xlUp).Row
Set sht = ThisWorkbook.Worksheets("STARSUN")
For lRow = 2 To LastRow
If sht.Cells(lRow, 4) = "SUN" Then
sht.Cells(lRow, 10).FormulaR1C1 = _
"=VLOOKUP(R[1]C[-8]&R[1]C[-1],OF_MOON!RC:RC[3], 4,0)"
ElseIf
If sht.Cells(lRow, 4) = "STAR" Then
sht.Cells(lRow, 10).FormulaR1C1 = _
"=VLOOKUP(R[1]C[-8]&R[1]C[-1],OFWORLD!RC:RC[3], 4,0)"
End If
Next lRow
End Sub
I think this train of thought should get you started. Remember that R1C1 has to be done in reference to the active cell that the formula will go in. I may need to check the rules for referring to new sheets but again, this should get you on the right line :) hope it helps
EDIT : Also, I believe you do need to set LastRow
I have added to the code
Dim LastRow as long
and
LastRow = Cells(Rows.Count, "D").End(xlUp).Row

Looks like you are missing definition and value of LastRow.
Use option explicit at the beginning of your modules to enforce variable declaration. Or simply Tools -> Options -> check Require Variable Declaration. It will be done automatically.
Also I do not understand why you would even use VBA for this. Can't you just use formula
=IF(cell="SUN",1st vlookup, if(cell="STAR", 2nd vlookup,NA())
Also I suggest using INDEX + MATCH instead of VLOOKUP.
And 3rd "also": you are hardcoding the key you will be looking up for: A3&G3. Thus You will get max of 3 values from your actions: Whatever is associated with A3&G3 in OF_MOON sheet or in OFWORLD sheet or #N/A.

Another way to get the result as below
Sub categoryVLOOKUP()
Dim lRow As Long, lCol As Long
Dim lRow2 As Long
Dim sht As Worksheet
LastRow = Range("D" & Rows.Count).End(xlUp).Row
Set sht = ThisWorkbook.Worksheets("STARSUN")
For lRow = 2 To LastRow
If sht.Cells(lRow, 4) = "SUN" Then
Range("K" & lRow).Value = Application.WorksheetFunction.VLookup(Range("A" & lRow) & Range("G" & lRow), Worksheets("OF_MOON").Range("A:D"), 4, 0)
ElseIf sht.Cells(lRow, 4) = "STAR" Then
Range("K" & lRow).Value = Application.WorksheetFunction.VLookup(Range("A" & lRow) & Range("G" & lRow), Worksheets("OF_MOON").Range("A:D"), 4, 0)
End If
Next lRow
End Sub

Related

Excel VBA with Index Match

Have been trying to solve below but no luck so far, seeking for your help :
vba formula return with extra two "#", how to fix the code or remove the "#" in cell R1?
If i want to do a loop and run the vba code from cell R1 to R30, which part of the code should i modify?
Dim PartPoError As Range
Dim PART As Range
Dim PO As Range
Dim lastrow As Long
lastrow1 = Sheets("TEMPLATE").Cells(Rows.Count, "A").End(xlUp).Row
x = "J" & lastrow1
t = "A" & lastrow1
V = "B" & lastrow1
Set PartPoError = Sheets("rpt_sense").Range("A1", x)
Set PART = Sheets("rpt_sense").Range("A1", t)
Set PO = Sheets("rpt_sense").Range("B1", V)
With Worksheets("rpt_sense")
.Range(.Cells(2, 23), .Cells(lastrow1, 23)).ClearContents
.Range(.Cells(2, 23), .Cells(lastrow1, 23)).Formula = "=A2&B2"
End With
lastrow2 = Sheets("template").Cells(Rows.Count, "A").End(xlUp).Row
For s = lastrow2 To 16 Step -1
If Sheets("template").Cells(s, 10).Value = "" Then
' Stuck in below formula error....it retunred with extra two "#" in cell formula R1.....
Sheets("template").Cells(s, 10) = "=INDEX('rpt_sense'!r:r" & ",MATCH('template'!c8" & "&'template'!B" & s & ",'rpt_sense'!a:a" & "&'rpt_sense'!f:f" & ",0),1)"
End If
Next s
picture file - index match id and date in yellow from another worksheet
picture 2 - data from another worksheet
I think you don't need vba code if you want to find the sales and revenue by id and date:
Here is the formula for finding the sales based on two criteria:
=INDEX(Sheet2!C2:C3,MATCH(1,INDEX((Sheet3!ID(cell)=Sheet2!A2:A3)*(Sheet3!date(cell)=Sheet2!B2:B3),0,1),0))
here
1.Sheet2 = where your data is stored.
2.sheet3 = where you want to find the sales and revenues
3.Use ID as absoulte reference
3.Use date as relative reference.
Let me know is it worked or not.
Sorry i don't understand fully what you wanted to do..Can you share screenshot with what your final output will be look like..
Dim PartPoError As Range
Dim PART As Range
Dim PO As Range
Dim lastrow As Long
lastrow1 = Sheets("TEMPLATE").Cells(Rows.Count, "A").End(xlUp).Row
'I think this variant variable is not required if you just want to use range.
x = "J" & lastrow1
t = "A" & lastrow1
V = "B" & lastrow1
'The change will be like this.
Set PartPoError = Sheets("rpt_sense").Range("A1","J" & lastrow1)
Set PART = Sheets("rpt_sense").Range("A1", "A" & lastrow1)
Set PO = Sheets("rpt_sense").Range("B1","B" & lastrow1)
With Worksheets("rpt_sense")
.Range(.Cells(2, 23), .Cells(lastrow1, 23)).ClearContents
.Range(.Cells(2, 23), .Cells(lastrow1, 23)).Formula = "=A2&B2"
End With
lastrow2 = Sheets("template").Cells(Rows.Count, "A").End(xlUp).Row
For s = lastrow2 To 16 Step -1
If Sheets("template").Cells(s, 10).Value = "" Then
'Please clear what actually you want to do here..
' Stuck in below formula error....it retunred with extra two "#" in cell formula R1.....
Sheets("template").Cells(s, 10) = "=INDEX('rpt_sense'!r:r" & ",MATCH('template'!c8" & "&'template'!B" & s & ",'rpt_sense'!a:a" & "&'rpt_sense'!f:f" & ",0),1)"
End If
Next s

Instr with If statement

Can someone please point out where I'm going wrong?
I want to delete certain rows if they fail to meet the criteria as provided in the code below.
I've tried Looping using the If statement and Instr function but not finding success.
Dim Firstrow As Integer
Dim Lastrow As Integer
Dim Lrow As Integer
Dim celltxt As String
Firstrow = 1
Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For Lrow = Lastrow To Firstrow Step -1
If InStr(Lrow, Range("ED" & Lrow), "FTOP") > 0 Then Sheets(Sheet1).Rows(Lrow).Delete
If InStr(Lastrow, LCase(Range("DT" & Lrow)), "BB") > 0 Then Sheets(Sheet1).Rows(Lrow).Delete
If Sheets(Sheet1).Cells(Lrow, "DX").Value = "SET" Then Sheets(Sheet1).Rows(Lrow).Delete
If Sheets(Sheet1).Cells(Lrow, "EM").Value = "=*AAA" Then Sheets(Sheet1).Rows(Lrow).Delete
Next Lrow
No error messages
I've modified your macro to loop through each row from the Lastrow to row 2, and if the value or string part is found in any of the four columns in the row, the row will be deleted. Combined all the IF statements into one using OR. Removed Lrow and Lastrow from the INSTR function, and put AAA into an INSTR function. Lrow was confusing so I removed and used i variable for the loop. Also added a workbook/worksheet reference variable.
Sub DeleteRowsThatMeetCriteria()
'Declare your variables
Dim ws As Worksheet, Lastrow As Long, i As Long
Set ws = ThisWorkbook.Sheets("Sheet1") 'Set the worksheet
Lastrow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row 'Assign the last row varaible
For i = Lastrow To 2 Step -1 'Assign "i" as a long number to loop from the last row to row 2
'Because you are testing different columns for different value and performing the same delete function,
'you can combine each test using OR, so you only need one IF statement. I removed "Lrow and Lastrow" variables
'because they were causing confusion and not needed inside the INSTR function. Since "SET" was the only full word
'i did not change it. But I used INSTR for "AAA" since it was part of a string.
If InStr(ws.Range("DT" & i), "BB") <> 0 _
Or ws.Range("DX" & i).Value = "SET" _
Or InStr(ws.Range("ED" & i), "FTOP") <> 0 _
Or InStr(ws.Range("EM" & i), "AAA") <> 0 Then
ws.Rows(i).Delete
End If
Next i 'DaLoop
End Sub

How can I iterate through a row, while using the sum formula for the column above in a for-loop?

I would like to iterate through a row, while summarizing the value of the columns above in a formula. At this point I have data from column 'A' to column 'AV'
The code below does what I want it do, but I'd like to get it into a for-loop that runs preferably to the last column with data. So that I don't have to write 40+ lines of repetitive code.
Dim LastRow As Long
LastRow = ThisWorkbook.Worksheets("Planteleveranse trær 2019").Range("F3").End(xlDown).Row
ThisWorkbook.Worksheets("Planteleveranse trær 2019").Cells(LastRow + 1, "F").Formula = "=SUM(F3:F" & LastRow & ")"
ThisWorkbook.Worksheets("Planteleveranse trær 2019").Cells(LastRow + 1, "L").Formula = "=SUM(L3:L" & LastRow & ")"
ThisWorkbook.Worksheets("Planteleveranse trær 2019").Cells(LastRow + 1, "M").Formula = "=SUM(M3:M" & LastRow & ")"
I think my questions was poorly asked, thanks for pointing that out. The code does what I want it do to, but I wish to extend it. I need to summarize the entire row from 'F' as I have done in my third line of code all the way column 'AV', and I expect more columns of data to be added in the future. I would like this done in a for loop like For char c = 'F' to c = 'AV' ThisWorkbook.Worksheets("Planteleveranse trær 2019").Cells(LastRow + 1, "c").Formula = "=SUM(c3:L" & LastRow & ")" But I do not know the syntax for that in vba. – Glenn Bergstrøm 11 mins ago
In that case I would recommend to find the last row and the last column. Identify your range and enter the formula in that range in one go as shown below. I have commented the code but if you still have a problem understanding it, feel free to ask :)
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim LastRow As Long, LastCol As Long
Dim myFormula As String
'~~> Set this to the relevant worksheet
Set ws = Sheet1
With ws
'~~> Find last row
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Find last column in row 1
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
'~~> Construct your formula
myFormula = "=Sum(A2:A" & LastRow & ")"
'~~> Enter formula in the entire range in 1 go
.Range(.Cells(LastRow + 1, 1), _
.Cells(LastRow + 1, LastCol)).Formula = myFormula
End With
End Sub
Screenshot:

Excel VBA offset function

I have an Excel file with information in column A and column B. Since these columns could vary in the number of rows I would like to use the function offset so that I could print the formula in one time as an array rather than looping over the formula per cell (the dataset contains almost 1 million datapoints).
My code is actually working the way I want it to be I only can't figure out how to print the code in Range(D1:D5). The outcome is now printed in Range(D1:H1). Anybody familiar how to use this offset within a for statement?
Sub checkOffset()
Dim example As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
Set example = Range("A1:A1")
For i = 1 To LastRow
example.Offset(0, i + 2).Formula = "=SUM(A" & i & ":B" & i & ")"
Next i
End Sub
Using the Offset(Row, Column), you want to offset with the increment of row (i -1), and 3 columns to the right (from column "A" to column "D")
Try the modified code below:
Set example = Range("A1")
For i = 1 To LastRow
example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")"
Next i
One way of outputting the formula in one step, without looping, to the entire range, is to use the R1C1 notation:
Edit: Code modified to properly qualify worksheet references
Option Explicit
Sub checkOffset()
Dim example As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
With sht
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set example = .Range(.Cells(1, 1), .Cells(LastRow, 1))
End With
example.Offset(columnoffset:=3).FormulaR1C1 = "=sum(rc[-3],rc[-2])"
End Sub
You don't need to use VBA for this. Simply type =sum(A1:B1) in cell D1 and then fill it down.
If you're going to use VBA anyway, use this:
Sub checkOffset()
Dim example As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("Sheet1")
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
Set example = Range("A1:A1")
For i = 1 To LastRow
example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")"
Next i
End Sub
The way offset works is with row offset, column offset. You want the column to always be fixed at 3 to the right.

Compare only some characters in a cell to only some characters in another cell

Hi guys I am running a macro in Excel 2003 to match property addresses to their owners addresses so I end up with a report of absentee owners.
So in:
column A column C
10 Smith DR Smithville 10 Smith DVE, Smithfield, 49089 Antartica
This is how some of the raw data has been input but I need for this record and all the other slightly different records to be a match and therefore not selected by the macro
as it searches for absentee owners addresses then populates the selected records to sheet2.
In laymans terms if I could compare say only the first 6 characters in column A to the first 6 characters in column C then I think it would work the way I need it to.
Does anyone know how I can achieve this within my macro shown below
Sub test()
Dim i As Long, lr As Long, r As Long, ws As Worksheet, value As Variant,
val As Variant
Dim sval As Integer, lr2 As Long
Application.ScreenUpdating = False
Set ws = Worksheets("Sheet1")
lr = ws.Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To lr
value = Split(Cells(i, 1).value, ", ")
For val = LBound(value) To UBound(value)
sval = InStr(1, Cells(i, 3).value, value(val), 1)
If sval = 0 Then Range("A" & i & ":" & "C" & i).Interior.Color = 65535
Next
Next
For r = 2 To lr
lr2 = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
If Range("A" & r).Interior.Color = 65535 Then
Rows(r).Copy Destination:=Sheets("Sheet2").Rows(lr2 + 1)
lr2 = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
End If
Next r
Sheets("Sheet2").Cells.Interior.ColorIndex = 0
Application.ScreenUpdating = True
MsgBox "Done Macro"
End Sub
Hopefully I have pasted the code in the correct format required here.
So any help and guidance would be much appreciated.
You can use the formula LEFT(). This will check the first 6 characters from the cell in column A to the first 6 characters in column C. If there's a match, it will add the value from column A to the next free cell in column A, Sheet2.
Sub First6Characters()
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
LastRowSheet2 = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To LastRow
If Left(Range("A" & i), 6) = Left(Range("C" & i), 6) Then
Sheets("Sheet2").Range("A" & LastRowSheet2).Value = Range("A" & i).Value
LastRowSheet2 = LastRowSheet2 + 1
End If
Next i
End Sub
Source: http://www.techonthenet.com/excel/formulas/left.php

Resources