Referencing a cells address and storing it in a Range object - excel

I am iterating through a column and wanting to catch the cells that meet the string of text that I am searching for. My problem occurs when I try and set the address of the cell that has met the criteria of the search into a Range object. Line:
Set testRng = i.Range.Adress
Gives me error " Wrong number of arguments or invalid property assignment" and I'm not sure what the issue is here?
This is the entire code I am working with:
Sub Tester()
Dim rng As Range
Dim testRng As Range
Dim i As Variant
Dim cmpr As String
Dim usrInputA As String
usrInputA = InputBox("Col 1 Criteria: ")
Set rng = Range("A2:A10")
For Each i In rng
cmpr = i.Value
If InStr(cmpr, usrInputA) Then
If testRng Is Nothing Then
Set testRng = i.Range.Address
Else
Set testRng = testRng & "," & i.Range.Address
End If
Else
MsgBox "No hit"
End If
Next
End Sub

You should declare i as a Range (not Variant)
Use Union to group together a collection of cells instead of trying to manually build the string yourself
Switch the order of your range set. You only need Set rngTest = i once so I would put this at the bottom so you don't have to keep spamming it.
Option Explicit
Sub Tester()
Dim testRng As Range, i As Range
Dim usrInputA As String
Dim LR as Long
usrInputA = InputBox("Col 1 Criteria: ")
LR = Range("A" & Rows.Count).End(xlUp).Row
For Each i In Range("A2:A" & LR)
If InStr(i, usrInputA) Then
If Not testRng Is Nothing Then
Set testRng = Union(testRng, i)
Else
Set testRng = i
End If
End If
Next i
If Not testRng is Nothing Then
'Do what with testRng?
End If
End Sub

Related

Trying to find all instances for a certain Text

I am trying to find all instances of a certain text within a range. I tried to creating a "Do Loop", but my loop keeps running, and doesn't time out.
Dim TextRange As Range
Dim LastRow As Long
Dim Cables As Range
LastRow = Report.Range("A" & Rows.Count).End(xlUp).Row
Set TextRange = rReport.Range("A20:AE" & RangeLastRow)
Set Cables = Report.Range("G20:G" & LastRow)
Dim cel As Range
Set cel = Cables.Cells.Find(what:=CableNumber)
If Not FindNumber Is Nothing Then 'If the number is found
Debug.Print CableNumber
Debug.Print FindCableNumber.Address
Do
Set FindNumber = Cables.FindNext(FindNumber)
Loop While Not FindNumber Is Nothing
Else 'If the cable number is not found
End If
The code you show is not complete and I am trying to deduce what you try accomplishing. I commented the strange lines, and changed the variables in a way to make it working. But I cannot be sure that what I suppose you really want accomplishing. Anyhow, please try understanding the next adapted code, test the suggested way and send some feedback:
Sub FandAllOccurrencesInRange()
Dim TextRange As Range 'not used
Dim LastRow As Long
Dim Cables As Range, Report As Worksheet, CableNumber
Set Report = Worksheets("Report") 'in case that Report is not the sheet code name
LastRow = Report.Range("A" & rows.Count).End(xlUp).row
'Set TextRange = rReport.Range("A20:AE" & RangeLastRow) 'not used
'is rReport a typo, or another undeclared, un set sheet?
Set Cables = Report.Range("G20:G" & LastRow)
CableNumber = "something" 'you must give a value to the variable to be searched!!!
Dim FindNumber As Range, firstAddress As String
Set FindNumber = Cables.Find(what:=CableNumber)
If Not FindNumber Is Nothing Then 'If the number is found
firstAddress = FindNumber.Address
Debug.Print CableNumber
Debug.Print FindCableNumber.Address
Do
Debug.Print FindNumber.Address
Set FindNumber = Cables.FindNext(FindNumber)
Loop While FindNumber.Address <> firstAddress
Else 'If the cable number is not found
End If
End Sub
It is good to know that FindNext returns in a loop, restarting iteration from the first occurrences. That's why firstAddress is necessary.

how to find multiple strings using range.value?

i tried to use range("A1:I1").value to find multiple strings at the first row however it shows that error "mismatch". What have i done wrong here? Is there another way to do it?
Dim sht as worksheet
Set sht = ThisWorkbook.Sheets("Result")
If sht.range("A1:I1").value = " Voltage" and sht.range("A1:I1").value = " Time" ,<---------error 'mismatch' occurs here
call powerandtime
The problem here is that you are comparing an array of values against a single value. In case of such a small array you can make use of some Application.Methods. Another option would be to use Range.Find on the actual Range object. I'll demonstrate both below:
Application.Methods
Sub Test()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Result")
Dim arr As Variant
With Application
arr = .Transpose(ws.Range("A1:I1").Value)
If .Count(.Match(Array("Voltage", "Time"), arr, 0)) = 2 Then
Call PowerAndTime
End If
End With
End Sub
What happens here is that .Match will return an array of two elements. It will either return an error value to the array if either "voltage" or "time" is not found, or it would return a numeric value when either one of them is found. Then .Count will count numeric values within that returned array, and only if the count would be 2, is when both values are present within your initial range.
Note: .Match needs a 1D-array, hence the .Transpose at the start.
Range.Find
Sub Test()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Result")
Dim rng1 As Range, rng2 As Range
Set rng1 = ws.Range("A1:I1").Find("Voltage", lookat:=xlWhole)
Set rng2 = ws.Range("A1:I1").Find("Time", lookat:=xlWhole)
If Not rng1 Is Nothing And Not rng2 Is Nothing Then
Call PowerAndTime
End If
End Sub
So only when both "Voltage" and "Time" are found as xlWhole values within your specific range, it would continue to call PowerAndTime.
Sub testMatchBis()
Dim sh As Worksheet, rng As Range, voltPos As Long, timePos As Long
Dim rngBis As Range, arrBis as Variant
Set sh = ActiveSheet ' use please your sheet here
Set rng = sh.Range("A1:I1")
voltPos = IsMatch(rng, "Voltage")
timePos = IsMatch(rng, "Time")
If voltPos <> 0 And timePos <> 0 Then
Set rngBis = sh.Columns(voltPos)
Set rngBis = Union(rngBis, sh.Columns(timePos))
arrBis = rngBis.Value 'the both columns content will be input in an array
rngBis.Select 'both columns will be selected. Of course, you need to determine
'only part of the comumn keeping values (their last row) and limit the range
'Call call powerandtime 'You must know what this sub must do...
Else
MsgBox "(At least) one of your searched strings could not be found in the range..."
End If
End Sub
Private Function IsMatch(rng As Range, strS As String) As Long
On Error Resume Next
IsMatch = WorksheetFunction.Match(strS, rng, 0)
If Err.Number <> 0 Then
Err.Clear: On Error GoTo 0
IsMatch = 0
End If
On Error GoTo 0
End Function
You could try:
Sub test()
Dim arrStrings As Variant
Dim i As Long, Counter As Long
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1:I1")
Counter = 0
arrStrings = Split("Time,Electric", ",")
For i = LBound(arrStrings) To UBound(arrStrings)
If Not rng.Find(arrStrings(i), lookat:=xlWhole) Is Nothing Then
Counter = Counter + 1
GoTo NextIteration
End If
NextIteration:
Next i
If Counter = UBound(arrStrings) + 1 Then
Call PowerAndTime
End If
End Sub

VBA - how to choose a column containing a specific cell and name it output column?

There is a cell in another worksheet whose value ranges from 1 to 100, I have defined its name as "SpanLength" in the name manager. In the worksheet I am now concerned with, I want to find the cell which contains the same value as "SpanLength", that is, a value from 1 to 100, within the range I have defined as "FindSpanLength". Then I want to call the column that this cell is within "outputcolumn" so that I can use this column further in the script. How can I do this?
The line of code before End Sub causes the error message 'Wrong number of arguments or invalid property assignment'
I am a VBA novice and no doubt my code is fraught with errors, so would appreciate any help I can get. I have already scoured google for answers but haven't found any specific enough for me to understand.
Sub OutputMaximums()
Dim spanlengthcell As Range
Set spanlengthcell = Range("FindSpanLength").Find("SpanLength")
Range("spanlengthcell").Column(1) = outputcolumn
End Sub
New Code, with error message 1004 (Method 'Range' of object '_Worksheet' failed):
Sub OutputMaximums()
Dim spanlengthcell As Range, outputcolumn As Long
Set spanlengthcell = OUTPUT.Range("FindSpanLength").Find(Range("SpanLength").Value)
If Not spanlengthcell Is Nothing Then
outputcolumn = spanlengthcell.Column
End If
End Sub
When you assign a value to a variable, the variable is on the left hand side of the equals sign.
When using Find always check first that your search term is found before trying to access its properties to avoid subsequent errors.
It is also advisable to specify a number of Find parameters as they may have unexpected settings from when last used on a worksheet.
Sub OutputMaximums()
Dim spanlengthcell As Range, outputcolumn As Long
Set spanlengthcell = Range("FindSpanLength").Find(Range("SpanLength").Value)
If Not spanlengthcell Is Nothing Then
outputcolumn = spanlengthcell.Column
End If
End Sub
Option Explicit
Sub test()
Dim rngSearch As Range, rngFound As Range
Dim strSearch As String
Dim ColumnNo As Long
strSearch = "Bingo"
With ThisWorkbook.Worksheets("Sheet1")
Set rngSearch = .UsedRange
Set rngFound = rngSearch.Find(strSearch)
If rngFound Is Nothing Then
MsgBox strSearch & " does not excist in range."
Else
ColumnNo = rngFound.Column
MsgBox "Text appears in column " & ColumnNo & "."
End If
End With
End Sub
Sub ShowNamedRange()
'The named Range "SpanLenght" must be on the Sheet "SheetWithNamedRange"!
Debug.Print Sheet("SheetWithNamedRange").Range("SpanLength").Address
Debug.Print Sheet("SheetWithNamedRange").Range("SpanLength").Column
End Sub
and after reading the question again:
Sub SearchRange()
Dim rngSearch As Range
Dim rngFound As Range
Dim strSearch As String
strSearch = Sheets("SheetWithNamedRange").Range("SpanLength").Value
Set rngSearch = Sheets("SheetWithFINDRange").Range("FindSpanLength")
Set rngFound = rngSearch.Find(strSearch)
If Not (rngFound Is Nothing) Then _
MsgBox "Found in column " & rngFound.Column & _
" on the sheet """ & rngFound.Parent.Name & """!"
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

How to select columns through VBA when the columns selectin reference is: A,E,D,S

I'm requesting a parameter from the user to specify columns (in Excel) to select, but am having some issues with converting the value to a string that I can use in VBA for reference.
I'm trying to avoid having the user enter A:A,E:E,D:D,S:S and instead just enter A,E,D,S in a cell. I'm sure the answer is right there but at the moment it's escaping me. Any suggestions?
Like I said,
Split on the , and iterate through the resultant array and build the range:
Sub fooooo()
Dim str As String
Dim rng As Range
Dim strArr() As String
str = "A,E,D,S" 'you can change this to the cell reference you want.
strArr = Split(str, ",")
With Worksheets("Sheet1") ' change to your sheet
Set rng = .Range(strArr(0) & ":" & strArr(0))
For i = 1 To UBound(strArr)
Set rng = Union(rng, .Range(strArr(i) & ":" & strArr(i)))
Next i
End With
Debug.Print rng.Address
End Sub
You can always turn this into a Function that returns a range:
Function fooooo(str As String, ws As Worksheet) As Range
Dim rng As Range
Dim strArr() As String
strArr = Split(str, ",")
With ws ' change to your sheet
Set rng = .Range(strArr(0) & ":" & strArr(0))
For i = 1 To UBound(strArr)
Set rng = Union(rng, .Range(strArr(i) & ":" & strArr(i)))
Next i
End With
Set fooooo = rng
End Function
Then you would call it like this from any sub you need:
Sub foofind()
Dim rng As Range
Dim str As String
str = "A,E,D,S"
Set rng = fooooo(str, Worksheets("Sheet1"))
Debug.Print rng.Address

Resources