How to formulate Index - Match to include conditions in VBA? - excel

I am trying to formulate an Index - Match function with three conditions:
Condition 1: It should check for only the highlighted cells
Condition 2: It should check for the same person in Scheduled Off Column
Condition 3: It should not repeat the same person again
I have two worksheets. On Sheet 1 I have the table with Positions against Employee. On Sheet2 I have the table where the Index match will be applicable. It also contains the Highlighted cells and drop down menu.
The Code should select name from the drop down list and not override the list
I have set Named Ranges in both the sheets. What I have tried is the following code.
Option Explicit
'use a constant to store the highlight color...
Const HIGHLIGHT_COLOR = 9894500 'RGB(100, 250, 150)'Is a cell highlighted?
EDIT: changed the function name to IsHighlighted
Function IsHighlighted(c As range)
IsHighlighted = (c.Interior.Color = HIGHLIGHT_COLOR)
End Function
Sub AssignBided()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim cel1 As range
Dim cel2 As range
Dim Bid As range
Dim line As range
Dim Offemp As range
Dim BidL8 As range
Dim BidL8E As range
Dim coresVal As String
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
Set Bid = ws2.range("Bid")
Set line = ws2.range("All_Pos_Hilight_Mon")
Set Offemp = ws2.range("Off_Mon") 'Scheduled Off Column
Set BidL8 = ws1.range("Bid_Pos") 'Bided Position
Set BidL8E = ws1.range("Bid_Emp") 'Bided Employee for a Position
For Each cel1 In BidL8E
For Each cel2 In line
If IsHighlighted(cel2) Then
If Application.WorksheetFunction.CountIf(Offemp, cel1.Value) > 0 Then
coresVal = Evaluate("Index(" & BidL8E.Address & "),MATCH(" & cel2.Validation & "," & BidL8.Address & ",0))")
Debug.Print coresVal
cel2.Offset(0, 2).Value = coresVal
End If
End If
Next cel2
Next cel1
End Sub
This code is not executing. I am getting the error:
Object doesn't support this property or method
It highlights line 33. If any one can help me in this it would be greatly appreciated. Thank you.

Related

Using CountIf to identify duplicate values

I have a question and it concerns using COUNTIF using VBA, I want to identify the occurrence of not all the data set range but if I pass in a specific value.
Code that I have looked at is:
For n = 5 To 11
If Application.CountIf(Range("CA2:CA7"), Range("C" & n)) > 1 Then
If Application.CountIf(Range("CA2:CA7"), Range("C" & n)) > 1 Then
Rng.Cells(i, 85).Value = "Stamp as a dulicate"
End If
Next n
The code looks at a range and identified duplicates but how can I pass in an attribute for example 123456 and look for all the duplicated values under 123456
This part I do not understand.
Hello Siddharth i don't need the count but if i am looking through a range of cells for example C2 to C11 I want to know where the occurrence is in a loop statement so when i come across the first occurrence i can mark it as found then the loop will move to the next occurrence and i can also mark it as found, keep on looping through the range of C2 to C11 until i have marked all the occurrences – user14156733
Not sure which one you want but I am giving you two procedures. You can use one of them. The first one searches for all occurences. The second one also searches for all occurences but only if there is a duplicate.
Option Explicit
Sub FindAllOccurances()
Dim ws As Worksheet
Dim rng As Range
Dim SearchText As Variant
Dim aCell As Range
Set ws = Sheet1
Set rng = ws.Range("C2:C11")
SearchText = 123456
For Each aCell In rng
If aCell.Value2 = SearchText Then
'~~> Do what you want here
Debug.Print "Found in " & aCell.Address
End If
Next aCell
End Sub
Sub FindAllOccurancesOnlyIfDuplicate()
Dim ws As Worksheet
Dim rng As Range
Dim SearchText As Variant
Dim aCell As Range
Set ws = Sheet1
Set rng = ws.Range("C2:C11")
SearchText = 123456
If Application.WorksheetFunction.CountIf(rng, SearchText) > 1 Then
For Each aCell In rng
If aCell.Value2 = SearchText Then
'~~> Do what you want here
Debug.Print "Found in " & aCell.Address
End If
Next aCell
End If
End Sub

Excel Row paste with VBA

Hi guys i need some help on VBA.
I have range of numbers in sheet 1 from cells A6:O29. Next I have specific numbers selected in Sheet 3 in Column "B".
[![enter image description here][1]][1]
[![enter image description here][2]][2]
I want to loop throw each value in Sheet 3 Column B and find that specific value in Sheet 1 range A6:O29
Next it should paste Entire Row from Sheet 1 starting From Column (Q:CF) in Sheet 3 Starting from Column C onwards
I have coded it but its not working.
Private Sub CommandButton1_Click()
Dim main As Worksheet
Dim outcome As Worksheet
'main sheet contains Range to search number in
Set main = ThisWorkbook.Sheets("Sheet1")
'outcome sheet has specific values in Column B
Set outcome = ThisWorkbook.Sheets("Sheet3")
'column B values are considrered as doubles
Dim valuesfind As Double
'range where values are to be found
Dim myrange As Range
Set myrange = Worksheets("Sheet1").Range("A6:O29")
'no of times to loop code based on values in outcomesheet
locations = Worksheets("Sheet3").Cells(Rows.Count, 2).End(xlUp).Row
For i = 6 To locations
degrees = outcome.Range("B" & i).Value
For b = 6 To Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
If main.Range("A6:O29" & b).Value = degrees Then
outecome.Range("C:BR" & i).Value = main.Range("Q:CF" & b).Value
Exit For
End If
Next b
Next i
End Sub
[1]: https://i.stack.imgur.com/uBo66m.png
[2]: https://i.stack.imgur.com/D0bRUm.png
Please remember to declare all variables, add Option Explicit at the top of your module to help you enforce it.
Try the code below:
Option Explicit
Private Sub CommandButton1_Click()
'main sheet contains Range to search number in
Dim main As Worksheet
Set main = ThisWorkbook.Sheets("Sheet1")
Const mainCopyRng As String = "Q?:CF?"
'outcome sheet has specific values in Column B
Dim outcome As Worksheet
Set outcome = ThisWorkbook.Sheets("Sheet3")
Const outcomePasteRng As String = "C?:BR?"
'range where values are to be found
Dim myrange As Range
Set myrange = main.Range("A6:O29")
'no of times to loop code based on values in outcomesheet
Dim outcomeLastRow As Long
outcomeLastRow = outcome.Cells(Rows.Count, 2).End(xlUp).Row
Dim i As Long
For i = 6 To outcomeLastRow
Dim Degrees As Double
Degrees = outcome.Cells(i, 2).Value
Dim searchRng As Range
Set searchRng = myrange.Find(Degrees, LookIn:=xlValues, LookAt:=xlWhole)
If Not searchRng Is Nothing Then
Dim searchRow As Long
searchRow = searchRng.Row
outcome.Range(Replace(outcomePasteRng, "?", i)).Value = main.Range(Replace(mainCopyRng, "?", searchRow)).Value
End If
Next i
End Sub
This should work.
Sub Test()
Dim main As Worksheet
Set main = ThisWorkbook.Sheets("Sheet1")
Dim myrange As Range
Set myrange = main.Range("A6:O29")
Dim outcome As Worksheet
Set outcome = ThisWorkbook.Sheets("Sheet3")
'Set reference to locations in sheet3.
Dim locations As Range
With outcome
Set locations = .Range(.Cells(1, 2), .Cells(Rows.Count, 2).End(xlUp))
End With
'Search for each location in Sheet1 and if found copy to Sheet3.
Dim location As Range
Dim FoundLocation As Range
For Each location In locations
Set FoundLocation = myrange.Find( _
What:=location, _
After:=myrange.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext)
If Not FoundLocation Is Nothing Then
main.Cells(FoundLocation.Row, 1).Resize(, 15).Copy _
Destination:=location.Offset(, 1)
End If
Next location
End Sub

Table lookup on a different workbook on fulfilling a criteria - Most efficient way

I have a table with 66 columns (representing the Wind turbines) and about 5000 rows of timestamps. I have to check if the value of each cell, in this case velocity, meets a certain criteria, if it does, i extract name of the Wind turbine from the topmost row. Using the name, i need to "lookup" the Wind turbine closest to it from a Matrix in a different sheet and return this.
Option Explicit
Public Sub ErsetzenNachbar()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim Arr As Variant
Dim Rng As Range
Dim SheetName As String
Dim i As Long
Dim j As Long
Dim WeaMat As Workbook
Dim Mat As Range
Dim Arr2 As Variant
Dim target As Long
Dim MOfound As String
SheetName = "INPUT_WIND"
'Range in the first Workbook
Set Rng = wb.Worksheets(SheetName).Range("C2:AG5000")
'Open the second Workbook
Set WeaMat = Workbooks.Open("C:\Users\Nikhil.srivatsa\Desktop\WeaMat")
'Set range for second workbook with the Matrix
Set Mat = WeaMat.Worksheets(1).Range("A2:AP68")
'Range into array
Arr = Rng.Value
'loop through array
For i = LBound(Arr, 1) To UBound(Arr, 1)
For j = LBound(Arr, 2) To UBound(Arr, 2)
If Arr(i, j) = 0.047 Then
'wind turbine Name from the topmost row
Arr(LBound(Arr, 1), j) = target
'look for target in the Matrix and fetch the neighboring turbine here is where i need help!
End If
Next j
Next i
End Sub
For example I look for the cells containing 0,047 (may vary) and get "MO30" the turbine name. Now i lookup MO30 in the Matrix of a second workbook and ask it to fetch MO42 from the Matrix since it is the first closest wind turbine.
would using Collections or Dictionary help in this case? or should I create an array out the Matrix? or use the Find function ?
Here is a simple example using two sheets rather than two workbooks, but see if you can adapt it for your set up.
Sub x()
Dim rFind1 As Range, s As String, rFind2 As Range
With Sheet1.Range("A1").CurrentRegion
Set rFind1 = .Find(what:=0.047, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False) 'look for value on sheet1
If Not rFind1 Is Nothing Then
s = .Rows(1).Cells(rFind1.Column) 'if found, find corresponding row 1 value
Set rFind2 = Sheet2.columns(1).Find(what:=s) 'look for this in sheet2
If Not rFind2 Is Nothing Then MsgBox rFind2.Offset(, 1) 'report contents of cell to the right
End If
End With
End Sub
Sheet1
Sheet2
Try this code, please:
Sub findTurb()
Dim sh As Worksheet, sh2 As Worksheet, rng As Range, strTurb As String
Const timeSt As Double = 0.047
Set sh = ActiveSheet 'use here your sheet
Set sh2 = Worksheets("second") 'use here your sheet
Set rng = sh.UsedRange.Find(timeSt)
If Not rng Is Nothing Then
strTurb = sh.Cells(1, rng.Column).value
Set rng = sh2.Range("A1:A" & sh2.Range("A" & Cells.Rows.Count).End(xlUp).Row).Find(strTurb)
If Not rng Is Nothing Then
MsgBox rng.Offset(, 1).value
End If
End If
End Sub
It can be transformed in a function, receiving time stamp as parameter and returning a string...

VBA extract unique values based on criteria

I want to get a list of distinct value based on a criteria, example : I have a list of stores, and i want to get only distinct value based on retailer criteria "BOULANGER".
Sub distinctValues()
Dim LastRow As Long
Dim Crit1 As String
LastRow = Sheets("SOURCE").Cells(Rows.Count, "B").End(xlUp).Row
Sheets("SOURCE").Range("B1:B" & LastRow).AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=Sheets("TEST").Range("E2"), CopyToRange:=Sheets("TEST").Range("A12"), Unique:=True
End Sub
I suspect your Criteria Range is not properly set up and/or named on your worksheet.
In the .AdvancedFilter, you have:
Range(Crit1)
which, according to your code, will be interpreted as:
Range("BOULANGER")
This presumes you have a Named Range somewhere on your Test Worksheet that is named BOULANGER and refers to two cells in a column, the first of which contains Store and the second contains BOULANGER
If you have that set up properly, then your code works.
Note that in your screen shot showing the criteria, the first cell contains Criteria and not Store. So even if you had the defined range setup to encompass those two cells, it would not work since the first row has to have an identical name to the column being filtered.
This should accomplish what you are trying to do; see comments in the code.
Sub ListUniqueValues()
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = ThisWorkbook.Sheets("Sheet1") 'change as needed
Set ws2 = ThisWorkbook.Sheets("Sheet2") 'change as needed
ws1.Range("B1", ws1.Cells(Rows.Count, "B").End(xlUp)).Copy ws2.Range("C1") 'copy the full range from sheet1
ws2.Range("C1", ws2.Cells(Rows.Count, "C").End(xlUp)).RemoveDuplicates Columns:=Array(1), Header:=xlNo 'remove duplicates
Dim lRow As Long
lRow = ws2.Cells(Rows.Count, 3).End(xlUp).Row 'set lastrow variable
For i = lRow To 1 Step -1 'Da Loop, from bottom to top
'change the cell address after "Like" to the cell address where you put your store criteria
'the line will delete any store name that is not like your store criteria
'the (& "*") inserts the wildcard after your store criteria you type in your designated cell, e.g. "BOULANGER*"
If Not ws2.Cells(i, 3).Value Like ws2.Cells(1, 1).Value & "*" Then '
ws2.Cells(i, 3).Delete 'delete the cells that do not match your store criteria
End If
Next i
End Sub
If you are trying to get a unique range that contains a keyword, something like this should work.
Option Explicit
Private Sub OutputUniqueRange(SearchRange As Range, Keyword As String, OutputRange As Range)
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim cell As Range
For Each cell In SearchRange
With cell
If InStr(1, .Value2, Keyword, vbTextCompare) > 0 And Not dict.exists(.Value2) Then dict.Add .Value2, .Value2
End With
Next
If dict.Count = 0 Then Exit Sub
OutputRange.Range(OutputRange.Cells(1, 1).Address).Resize(dict.Count, 1) = Application.Transpose(dict.items())
End Sub
Public Sub TestSub()
Dim SearchRange As Range
Dim Keyword As String
Dim OutputRange As Range
Keyword = "Boulanger"
Set SearchRange = ThisWorkbook.Sheets("Sheet1").Range("A2:A34")
Set OutputRange = ThisWorkbook.Sheets("Sheet1").Range("B2")
OutputUniqueRange SearchRange, Keyword, OutputRange
End Sub

Match a value from the table to a dropdown range

I have been trying this for a while now and am not able to figure out the for code for this problem.
I have a table in sheet1 with two columns, in one column I have positions, in the next I have people who can work on those positions.
In sheet2 I have the list of all the positions and the one that are supposed to be staffed are highlighted when you select a SKU, and two columns besides it is the dropdown list of the employees.
This same sheet also has a range which displays employee who are not working that day.
Tried to implement #BruceWayne answer the code is:
Option Explicit
'use a constant to store the highlight color...
Const HIGHLIGHT_COLOR = 9894500 'RGB(100, 250, 150)
Sub AssignBided()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim cel1 As range
Dim cel2 As range
Dim line8 As range
Dim Offemp As range
Dim BidL8 As range
Dim BidL8E As range
Dim coresVal As String
Set ws1 = Worksheets("OT_Table")
Set ws2 = Worksheets("Monday")
Set line8 = ws2.range("Line8_Hilight_Mon")
Set Offemp = ws2.range("Off_Mon")
Set BidL8 = ws1.range("BidedL8")
Set BidL8E = ws1.range("BidedL8_E")
For Each cel2 In BidL8E
For Each cel1 In line8
If IsHighlighted(cel1) Then
If Application.WorksheetFunction.CountIf(Offemp, cel2.Value) > 0 Then
coresVal = Evaluate("Index(" & BidL8E.Address & "),MATCH(" & cel1.Validation & "," & BidL8.Address & ",0))")
Debug.Print coresVal
cel1.Offset(0, 2).Value = coresVal
End If
End If
Next cel1
Next cel2
End Sub
'Is a cell highlighted? EDIT: changed the function name to IsHighlighted
Function IsHighlighted(c As range)
IsHighlighted = (c.Interior.Color = HIGHLIGHT_COLOR)
End Function
This code is giving me this error: Object doesn't support this property or method. It highlights the evaluate line. Am I using this in some wrong manner?
From the comments, I think this is what you are trying to do.
(I renamed some variables to make them a little easier to understand. Also, adjust the named ranges as needed. They may not all be on the "OT_Table" sheet, which I assumed they were. It wasn't clear.)
Sub AssignBided()
Dim ws As Worksheet
Set ws = Worksheets("OT_Table")
Dim cel As Range
Dim line8 As Range
Set line8 = ws.Range("Line8_Highlight_Mon")
Dim Offemp As Range
Set Offemp = ws.Range("Scheduled_Off")
Dim BidL8 As Range
Set BidL8 = ws.Range("BidedL8_T")
Dim coresVal As String
For Each cel In line8
' cel.Select
If IsHighlighted(cel) Then
If Application.WorksheetFunction.CountIf(Offemp, cel.Value) > 0 Then
coresVal = Evaluate("INDEX(OFFSET(" & BidL8.Address & ",,2),MATCH(" & _
cel.Value & "," & BidL8.Address & ",0))")
Debug.Print coresVal
cel.Offset(0, 2).Value = coresVal
End If
End If
Next cel
End Sub

Resources