Excel VBA with Index Match - excel

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

Related

VBA Looping cells and Copy based on criteria

[Copy A2 to E2 till the end of row of the table and check if the cell is within the same month](https://i.stack.imgur.com/Q7YAx.png)
Hi,
I would like to loop through rows from a sheet table from column A2 to E2 to A3 to E3... till the end of the table Ai to Ei by defining a variable and counting the last row of the table.
As the second step, I would like to copy the cells into another sheet and fill it the corresponding months.
[Desired Output--> it will copy the data and return to another sheet in the corresponding month] (https://i.stack.imgur.com/zhgYh.png)
Instead, I've changed the data type into a number format and have set up two condition to loop through.
eg. 1/1/2017 change to 42736
28/2/2017 change to 42794
Sub Mike_Copy_cell()
Dim i As Long 'for looping inside each cell
Dim myvalue As Variant
Dim Lastrow As Long
Const StartRow As Byte = 2
Dim LastMonth As Long
("Mike Filter").Select
Lastrow = Range("A" & StartRow).End(xlDown).Row
For i = StartRow To Lastrow
myvalue = Range("H" & i).Value
If myvalue \< Sheets("Automate Report").Range("A" & i).Value \_
'First data Feb Data 42794 \< Jan Category 42736
Then Sheets("Automate Report").Range("B" & i).Value = ""
'leave the cells in blanks and loop through next cell
If myvalue > Sheets("Automate Report").Range("A" & i).Value _
'First data Feb Data 42794 > Jan Category 42736
Then Range("A" & i, "E" & i).Copy Sheets("Automate Report").Range("B" & i, "F" & i)
'Copy the cells into corresponding category
Next i
End sub()
In my output, it is able to loop through and copy all the cells. However, I am wondering the reason why VBA output is not able leave any blank cells when the first condition is met ?
**I am expecting some blanks in the table if it is not data is not within the same month or in my case is less than criteria I have set. **
The output of my code
If myvalue < Sheets("Automate Report").Range("A" & i).Value _
Then Sheets("Automate Report").Range("B" & i).Value = ""
Greatly appreciate if you can advise the flaws in my code. Massive Thanks.
Best regards,
Kenneth
I'll try to help. But before, may I give you two suggestions that might help you?
First, for me the best way to find the last row is, instead of using xldown from the first row, using xlup from the very last row of excel. This way, if there is a blank in any middle row, the code still gives you the last row with value.
Second, I found that referring to any cells with the "range" method may limit you sometimes when using variables in this reference. I think using the "cells(row, column)" method is more useful.
Why not trying this?
Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Sorry for the suggestions, It's just that I wish someone had taught them to me sooner.
Back to the topic, I think the problem is how you structure the "if" statement. Allow me to change it a bit:
Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For i = StartRow To Lastrow
myvalue = cells(i, 8).Value
'if myvalue date is equal or previous to the one found in Ai...
If myvalue <= Sheets("Automate Report").cells(i, 1).Value then
Sheets("Automate Report").cells(i, 2).Value = ""
'but if myvalue is later than Ai...
else
sheets("Automate Report").select
range(cells(i, 1), cells(i, 5).select
selection.copy
cells(i, 2).select
activesheet.paste
end if
Next i
Hope this helps. Best regards,
Mike
I'm not sure what your code is doing but consider using an array(12) of row numbers, one for each month. Copy lines into corresponding month and increment the row number for that month. For example ;
Option Explicit
Sub Mike_Copy_cell()
Const LINES_MTH = 5 ' lines per month
Dim wb As Workbook
Dim wsIn As Worksheet, wsOut As Worksheet
Dim lastrow As Long, rIn As Long, rOut(12) As Long
Dim uid As String, prevuid As String
Dim dAVD As Date, m As Long, n As Long
Set wb = ThisWorkbook
Set wsIn = wb.Sheets("Mike Filter")
Set wsOut = wb.Sheets("Automate Report")
' space out months
For n = 0 To 11
rOut(n + 1) = 2 + n * LINES_MTH
wsOut.Cells(rOut(n + 1), "A").Value2 = MonthName(n + 1)
Next
n = 0
With wsIn
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For rIn = 2 To lastrow
dAVD = .Cells(rIn, "D")
' create a unique ID to skip duplicates
uid = .Cells(rIn, "A") & Format(.Cells(rIn, "D"), "YYYY-MM-DD")
If uid <> prevuid Then
m = Month(dAVD)
.Cells(rIn, "A").Resize(, 5).Copy wsOut.Cells(rOut(m), "B")
rOut(m) = rOut(m) + 1
n = n + 1
End If
prevuid = uid
Next
End With
MsgBox n & " lines copied to " & wsOut.Name, vbInformation
End Sub

How to delete entire row except column A in VBA loop?

I'm trying to highlight the entire row grey if the value in column A begins with "ABC" as well as delete everything right of that cell. Any ideas on how to do this?
Dim DataRange As Range
Set DataRange = Range("A1:U" & LastRow)
Set MyRange = Range("A2:A" & LastRow)
For Each Cell In MyRange
If UCase(Left(Cell.Value, 3)) = "ABC" Then
Cell.EntireRow.Interior.ColorIndex = 15
Else
End If
Next
Here is pretty straightforward approach:
Dim lastRow As Long
Dim row As Long
Dim temp As String
' insert your sheet name here
With ThisWorkbook.Worksheets("your sheet name")
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' you can change the starting row, right now its 1
For row = 1 To lastRow
' store whats in col A in a temporary variable
temp = Trim(CStr(.Range("A" & row).Value))
' if col A isn't 'ABC' clear & grey entire row
If UCase(Left(.Range("A" & row).Value), 3) <> "ABC" Then
.Rows(row).ClearContents
.Rows(row).Interior.ColorIndex = 15
' place temp variable value back in col A and make interior No Fill
.Range("A" & row).Value = temp
.Range("A" & row).Interior.ColorIndex = 0
End If
Next
End With
Here is another example; you stated "clear everything to the right" so I added offset to clear the contents of the cells not in column A.
Dim x As Long
For x = 1 To Cells(Rows.Count, 1).End(xlUp).Row
If UCase(Left(Cells(x, 1).Value, 3)) = "ABC" Then
Range(Cells(x, 1), Cells(x, Columns.Count).End(xlToLeft)).Interior.ColorIndex = 15
Range(Cells(x, 1).Offset(, 1), Cells(x, Columns.Count).End(xlToLeft)).ClearContents
End If
Next x

IF statement including VLOOKUP

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

Convert Text to Rows instead of Text to Columns

I have a text string that is using the ^ symbol as a delimiter.
I need to separate the text into new rows rather than new columns.
I need to create new rows to not overwrite the next line of data below it.
Is this possible without using a macro? I'm not against using one, I just wouldn't know where to start to write it.
Below is a pic of some sample data. The top part is how it's listed, and the bottom (in yellow) is how I would like it.
Using Excel 2010 on Windows 7 Pro.
Thanks to those that responded. A friend was able to help by providing the following code:
Sub Breakout()
Application.ScreenUpdating = False
LR = Cells(Rows.Count, 1).End(xlUp).Row
For r = LR To 2 Step -1
Set MyCell = Cells(r, 1)
Arry = Split(MyCell.Value, "^")
For c = 0 To UBound(Arry)
If c > 0 Then MyCell.Offset(c, 0).EntireRow.Insert
MyCell.Offset(c, 0) = Arry(c)
Next c
Next r
End Sub
Could try something like this:
Sub reArrange()
Dim inFirstRng As Range
Dim inRng As Range
Dim inCur As Variant
Dim outFirstRng As Range
Dim outCurRng As Range
Dim ws As Worksheet
'CHANGE ARGUMENT TO YOUR SHEET NAME
Set ws = Worksheets("Sheet2")
With ws
'CHANGE ARGUMENT TO WHATEVER THE FIRST CELL OR YOUR DATA INPUT IS IN COLUMN A
Set inFirstRng = .Range("A3")
Set inRng = .Range(inFirstRng, inFirstRng.End(xlDown))
'CHANGE ARGUMENT TO WHATEVER THE FIRST CELL OR YOUR DATA OUTPUT IS IN COLUMN A
Set outFirstRng = .Range("A9")
Set outCurRng = outFirstRng
End With
For Each cell In inRng.Cells
inCur = WorksheetFunction.Transpose(Split(cell.Value, "^"))
outCurRng.Resize(UBound(inCur), 1).Value = inCur
With ws
.Range("G" & outCurRng.Row & ":L" & outCurRng.Row).Value = _
.Range("G" & cell.Row & ":L" & cell.Row).Value
End With
Set outCurRng = outCurRng.Offset(UBound(inCur), 0)
Next cell
ws.Range("F" & outFirstRng.Row & ":F" & outCurRng.Row - 1).Value = 1
End Sub

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