Looping Word Match Function in Excel VBA - vba

I have a list of keywords and want to see if one cell contains any one of these words. For example if my list of keywords is (Cat, Dog, Turtle) the function would return MATCH if it was looking inside "Mr. Dogs Magic Land". I have found a good UDF online to use as the function but when I try to loop it so it tests every word on my keyword list I get #VALUE!. The first function is my loop while the second is the UDF match function found on the internet (sorry don't remember where but props to whoever made it.) I've tried variations of word match functions such as InStr to no avail.
Function StringFind(rng(), source)
For I = LBound(rng) To UBound(rng)
StringFind = MyMatch(rng(I), source)
If StringFind = "MATCH" Then Exit Function
Next I
StringFind = "NO MATCH"
End Function
Function MyMatch(FindText As String, WithinText As Variant) As String
'
Dim vntFind As Variant
Dim vntWithin As Variant
For Each vntFind In Split(UCase(FindText), " ")
If Len(Trim(vntFind)) > 0 Then
For Each vntWithin In Split(UCase(WithinText), " ")
If Len(Trim(vntWithin)) > 0 Then
If vntFind = vntWithin Then
MyMatch = "MATCH"
Exit Function
End If
End If
Next
End If
Next
MyMatch = "NO MATCH"
End Function

1) FORMULA
I would first offer the non-VBA solution to this particular problem since VBA isn't really needed. This array formula will do the same thing. Enter the array by pressing CTRL-SHIFT-ENTER, you'll see the curly braces { } appear around your formula. Then you can copy down.
'=IF(OR(ISNUMBER(SEARCH($F$1:$F$3, A1))), "Match", "No Match")
2) UDF
Using the same syntax as yours, here's how I might approach this with a UDF.
Function MySearch(MyRNG As Range, MyStr As String) As String
Dim cell As Range
For Each cell In MyRNG
If LCase(MyStr) Like LCase("*" & cell & "*") Then
MySearch = "Match"
Exit Function
End If
Next cell
MySearch = "No Match"
End Function

Plugged this in as-is in my VBE, and I couldn't even compile.
This line
StringFind = MyMatch(rng(I), source)
needs to be changed to
StringFind = MyMatch(rng(I).Value, source)
to even get it to work for me. This MAY be the cause of your problem.
EDIT
Ok, I reviewed all in more detail. It looks like this will work for you. (Sorry, I didn't mean to just do it all for you, but here it is.) It probably needs some more tweaking to make it work for your needs.
The problem was that you were looking for undefined data types (added/changed main function call to As String and As Range). While the undefined types can work, I think it was confusing in seeing why the problem was coming up. I tried to set a breakpoint in the function and never even got that far because the wrong data type was being passed. Personally, I always use Option Explicit to help prevent issues like this from arising in my own code.
The below code will now look for the value in the first argument(Search, can be a "" text/String or a single cell/Range) against all the values in the second argument (Source a Range consisting of either a single or multiple cells).
Public Function StringFind(Search As String, Source As Range)
Dim rngCell As Range
For Each rngCell In Source.Cells
StringFind = MyMatch(Search, rngCell.Value)
If StringFind = "MATCH" Then Exit Function
Next rngCell
StringFind = "NO MATCH"
End Function
Function MyMatch(FindText As String, WithinText As Variant) As String
'
Dim vntFind As Variant
For Each vntFind In Split(UCase(FindText), " ")
If Len(Trim(vntFind)) > 0 Then
If vntFind = Trim(UCase(WithinText)) Then
MyMatch = "MATCH"
Exit Function
End If
End If
Next
MyMatch = "NO MATCH"
End Function

Related

Why SumProduct cannot use in Excel VBA

Scenario
I am trying to use COUNTIF in my VBA code to count total how many similar string found in a range. But realised COUNTIF is not case sensitive. Eg: I want to count how many Apple in a range. But sometimes if in that range got apple, it is counting that also. Code as below. Consider Range(poRange) something like C1:C100 and Trim(mainpage.po.value) as Apple
iVal = Application.WorksheetFunction.CountIf(Range(poRange), Trim(mainPage.po.Value))
Thus I decided to use another method which is
iVal = Application.WorksheetFunction.SumProduct(--(EXACT(Range(poRange), Trim(mainPage.po.Value))))
But this time I couldn't run my VBA due to Compile time error 'Sub or Function not defined'
Could someone help me please?
The issue is with the EXACT function, which WorksheetFunction does not expose.
For unexposed Excel functions, a common workaround is to convert the expression to a string and call the Evaluate function. A rudimentary routine would look like this:
Public Function SumProductExact(rng As Range, testItem As String) As Long
Dim evalExpr As String
On Error GoTo EH
evalExpr = "=SUMPRODUCT(--(EXACT(" & rng.Address & ", """ & testItem & """)))"
SumProductExact = Evaluate(evalExpr)
Exit Function
EH:
SumProductExact = -1
End Function
and would be called like so:
Debug.Print SumProductExact(Sheet1.Range("A1:A10"), "Apple")
But it hardly seems worth going to those lengths for a relatively trivial function, so you could just write your own CountIf function for an exact match. You might want to expand this to cater for other type comparisons, like dates, but fundamentally it would look like this:
Public Function CountIfExact(rng As Range, testItem As Variant) As Long
Dim v As Variant
Dim c As Long
On Error GoTo EH
For Each v In rng.Value2
If v = testItem Then c = c + 1
Next
CountIfExact = c
Exit Function
EH:
CountIfExact = -1
End Function
which would be called as follows:
Debug.Print CountIfExact(Sheet1.Range("A1:A10"), "Apple")
I used one of the above solutions and it solved the problem. Entire code as below
Public c As Integer
Sub findVal()
Call SumProductExact(Sheet1.Range("A1:A10"), "Apple")
MsgBox c ' You can use this c value for other calculations
End Sub
Public Function SumProductExact(rng As Range, testItem As String) As Long
Dim evalExpr As String
On Error GoTo EH
evalExpr = "=SUMPRODUCT(--(EXACT(" & rng.Address & ", """ & testItem & """)))"
SumProductExact = Evaluate(evalExpr)
c = SumProductExact
Exit Function
EH:
SumProductExact = -1
End Function
Take note that for the above code, it is using static range which is A1:A10 and a static name Apple. You may change it to a dynamic range and name according to your needs.

Search cell for text and copy text to another cell in VBA?

I've got a column which contains rows that have parameters in them. For example
W2 = [PROD][FO][2.0][Customer]
W3 = [PROD][GD][1.0][P3]
W4 = Issues in production for customer
I have a function that is copying other columns into another sheet, however for this column, I need to do the following
Search the cell and look for [P*]
The asterisk represents a number between 1 and 5
If it finds [P*] then copy P* to the sheet "Calculations" in column 4
Basically, remove everything from the cell except where there is a square bracket, followed by P, a number and a square bracket
Does anyone know how I can do this? Alternatively, it might be easier to copy the column across and then remove everything that doesn't meet the above criteria.
Second Edit:
I edited here to use a regular expression instead of a loop. This may be the most efficient method to achieve your goal. See below and let us know if it works for you:
Function MatchWithRegex(sInput As String) As String
Dim oReg As Object
Dim sOutput As String
Set oReg = CreateObject("VBScript.RegExp")
With oReg
.Pattern = "[[](P[1-5])[]]"
End With
If oReg.test(sInput) Then
sOutput = oReg.Execute(sInput)(0).Submatches(0)
Else
sOutput = ""
End If
MatchWithRegex = sOutput
End Function
Sub test2()
Dim a As String
a = MatchWithRegex(Range("A1").Value)
If a = vbNullString Then
MsgBox "None"
Else
MsgBox MatchWithRegex(Range("A1").Value)
End If
End Sub
First EDIT:
My solution would be something as follows. I'd write a function that first tests if the Pattern exists in the string, then if it does, I'd split it based on brackets, and choose the bracket that matches the pattern. Let me know if that works for you.
Function ExtractPNumber(sInput As String) As String
Dim aValues
Dim sOutput As String
sOutput = ""
If sInput Like "*[[]P[1-5][]]*" Then
aValues = Split(sInput, "[")
For Each aVal In aValues
If aVal Like "P[1-5][]]*" Then
sOutput = aVal
End If
Next aVal
End If
ExtractPNumber = Left(sOutput, 2)
End Function
Sub TestFunction()
Dim sPValue As String
sPValue = ExtractPNumber(Range("A2").Value)
If sPValue = vbNullString Then
'Do nothing or input whatever business logic you want
Else
Sheet2.Range("A1").Value = sPValue
End If
End Sub
OLD POST:
In VBA, you can use the Like Operator with a Pattern to represent an Open Bracket, the letter P, any number from 1-5, then a Closed Bracket using the below syntax:
Range("A1").Value LIke "*[[]P[1-5][]]*"
EDIT: Fixed faulty solution
If you're ok with blanks and don't care if *>5, I would do this and copy down column 4:
=IF(ISNUMBER(SEARCH("[P?]",FirstSheet!$W2)), FirstSheet!$W2, "")
Important things to note:
? is the wildcard symbol for a single character; you can use * if you're ok with multiple characters at that location
will display cell's original value if found, leave blank otherwise
Afterwards, you can highlight the column and remove blanks if needed. Alternatively, you can replace the blank with a placeholder string.
If * must be 1-5, use two columns, E and D, respectively:
=MID(FirstSheet!$W2,SEARCH("[P",FirstSheet!$W2)+2,1)
=IF(AND(ISNUMBER($E2),$E2>0,$E2<=5,MID($W2,SEARCH("[P",FirstSheet!$W2)+3,1))), FirstSheet!$W2, "")
where FirstSheet is the name of your initial sheet.

How do I find a value in a row and return the column number with VBA?

My excel sheet is filled with zeroes except for one cell in every row.
I want to find that cell and return the column.
For example: In the cell T616 is a value other than 0. May it be -15400.
I want to find that cell(T616) based on the row(616) and have the column returned(T). May it even be in a MsgBox.
This is my result of many tries and long Google-sessions:
Public Function find_Column(lRange As Range, lValue As String) As Integer
Dim vCell As Range
For Each vCell In lRange.Cells
If vCell.Value = lValue Then
find_Column = vCell.Column
MsgBox (find_Column)
Exit Function
End If
Next vCell
End Function
I found this code somewhere and modified it a little bit, but I can't remember where. So thanks to the creator!
How do I search for a number other than 0?
I'm relatively new to VBA and don't really have an idea what I am doing. Sorry for my bad English (foreigner). I'd appreciate any help. Thank you!
Try this:
Public Function findNonZeroValueInColumn(lRange As Range) As Integer
Dim vCell As Range
For Each vCell In lRange.Cells
If vCell.Value <> 0 Then
find_Column = vCell.Column
Exit Function
End If
Next vCell
End Function
Sub ShowValue()
call MsgBox(findNonZeroValueInColumn(Range("A:A")))
End Sub
Remember that Functions are supposed to return values. Subs (Procedures) do not return values.
The <> symbol is the "Not Equal" Comparison. So if you wanted to check if a cell didn't equal 0, you would write
If vCell.Value <> 0 Then
... ' rest of code here
In your problem:
Public Function find_Column(lRange As Range) As Integer
Dim vCell As Range
For Each vCell In lRange.Cells
If vCell.Value <> 0 Then
find_Column = vCell.Column
MsgBox (find_Column)
Exit Function
End If
Next vCell
End Function
Also since you are only checking against 0, you wouldn't need the extra lValue As String argument.
As the other part of your question has been answered while I was typing, if you want to return the column letter instead of the number...
find_Column = Replace(Replace(vCell.Address, vCell.Row, ""), "$", "")
If this is what you want the function to return, you would have to change the type your function is returning to string

In Excel 2010, how could I remove duplicates and concatenate values within a cell range that includes multiple values cells?

I made a document in Excel 2010 however, the functionality I'm hoping to get from it doesn't seem to be possible (at least not with the default Excel functions) and I don't know enough about VB programming to make my own UDF. (I'm actually using one I found online which does part of what I want, but doesn't meet all of my needs.)
Let me break it down:
I have multiple sheets with groups of fields where users can add numbers (some will be blank, some will contain a single number, some will contain multiple comma-separated numbers)
I have an "Overview" sheet where I want to Concatenate those numbers (and remove any duplicates) within a few different sections (only looking at specific field groups).
I found a ConcatIf UDF that works fairly well for this, however it can't handle non-consecutive cells to concatenate (For example, I want to concatenate and remove duplicates from cells D30, G30, J30 and M30 together) (Here's the UDF:)
Function ConcatIf(ByVal compareRange As Range, ByVal xCriteria As Variant, Optional ByVal stringsRange As Range, _
Optional Delimiter As String, Optional NoDuplicates As Boolean) As String
Dim i As Long, j As Long
With compareRange.Parent
Set compareRange = Application.Intersect(compareRange, Range(.UsedRange, .Range("a1")))
End With
If compareRange Is Nothing Then Exit Function
If stringsRange Is Nothing Then Set stringsRange = compareRange
Set stringsRange = compareRange.Offset(stringsRange.Row - compareRange.Row, _
stringsRange.Column - compareRange.Column)
For i = 1 To compareRange.Rows.Count
For j = 1 To compareRange.Columns.Count
If (Application.CountIf(compareRange.Cells(i, j), xCriteria) = 1) Then
If InStr(ConcatIf, Delimiter & CStr(stringsRange.Cells(i, j))) <> 0 Imp Not (NoDuplicates) Then
ConcatIf = ConcatIf & Delimiter & CStr(stringsRange.Cells(i, j))
End If
End If
Next j
Next i
ConcatIf = mid(ConcatIf, Len(Delimiter) + 1)
End Function
It also can't handle the "multiple numbers in one cell" as separate numbers.
Is there a way to make a Concatenate UDF that "parses" the cells it's looking at to look for duplicates between the multiple numbers cells and the single numbers cells, and then output the result? Preferably allowing it to take a series of non-consecutive cells to work on (across different sheets).
Sorry if the explanation is a bit convoluted, it's my first time asking for this kind of help. :x
Here's an example:
If I have cells with:
2,4,6
2,6
2
4
6
6,8
I'd want to be able to simply get:
2,4,6,8
Right now, instead, I'd get:
2,4,6,2,6,6,8
Try the below. You can adapt it appropriately if you need to change the delimiter etc. I have documented what it is doing and why.
Example formula: =blah(A1:A7,A8,C9) (it can also be called from code)
Example output: 2,4,6,8
Public Function Blah(ParamArray args()) As String
'Declarations
Dim uniqueParts As Collection
Dim area As Range
Dim arg, arr, ele, part
Dim i As Long
'Initialisations
Set uniqueParts = New Collection
'Enumerate through the arguments passed to this function
For Each arg In args
If TypeOf arg Is Range Then 'range so we need to enumerate its .Areas
For Each area In arg.Areas
arr = area.Value 'for large ranges it is greatly quicker to load the data at once rather than enumerating each cell in turn
For Each ele In arr 'enumerate the array
addParts CStr(ele), uniqueParts 'Call our sub to parse the data
Next ele
Next area
ElseIf VarType(arg) > vbArray Then 'an array has been passed in
For Each ele In arg 'enumerate the array
addParts CStr(ele), uniqueParts 'Call our sub to parse the data
Next ele
Else 'assume can be validly converted to a string. If it cannot then it will fail fast (as intended)
addParts CStr(arg), uniqueParts 'Call our sub to parse the data
End If
Next arg
'process our results
If uniqueParts.Count > 0 Then
ReDim arr(0 To uniqueParts.Count - 1)
For i = 1 To uniqueParts.Count
arr(i - 1) = uniqueParts(i)
Next i
'we now have an array of the unique parts, which we glue together using the Join function, and then return it
Blah = Join(arr, ",")
End If
End Function
'Sub to parse the data. In this case the sub splits the string and adds the split elements to a collection, ignoring duplicates
Private Sub addParts(partsString As String, ByRef outputC As Collection)
'ByRef is unecessary but I use it to document that outputC must be instantiated
Dim part
For Each part In Split(partsString, ",")
On Error Resume Next 'existing same key will raise an error, so we skip it and just carry on
outputC.Add part, part
On Error GoTo 0
Next part
End Sub

VBA Range.value function causing unexpected end

This must seem like a terribly simple question, but I cannot figure out why my functions are ending unexpectedly on the Range.value = val call. Perhaps I am missing something very basic, but I have tested these out and each one of them are failing to resolve to anything and I don't know how to capture the error.
Here is the initial function:
Function incrementCount(upper As Range, Summed As Range, ParamArray sums() As Variant)
Dim deduct As Integer
Dim summation As Integer
Dim elem As Variant
Dim i As Long
Dim temp As Range
up = upper.Value
summation = Summed.Value
'Initialize the starting points of the increments
For i = LBound(sums) To UBound(sums)
MsgBox IsObject(sums(i)) 'Prints out as an true
MsgBox TypeName(sums(i)) 'Prints out as Rnage
MsgBox sums(i).Value 'Prints out as 0
Set temp = sums(i)
MsgBox temp.Value 'Prints out as 0
Set temp = Summed
MsgBox temp.Value 'Prints out as 1 (which is correct)
temp.value = 3 'Errors here
MsgBox temp.Value 'Never makes it to this line
sums(i).Value = 1 'I have also tried this with the same result
Next i
<more code that is never reached>
End Function
I am at my wits end. I have searched MSDN, stackoverflow, and all the many excel forums and all of them show setting values to a range like this. I have even separated the setting of a range value to a different function like this:
Function testsub(thecell As Range, thevalue As Integer)
thecell.value = thevalue
End Function
Ultimately i would like to be able to do something like discussed in this article where I loop over a random assortment of ranges and will increment them. Any help at all would be greatly appreciated.
You have not specified how IncrementCount() is being called.
If your function is being called from a worksheet cell, then it is "bombing out" at the correct line. A UDF called from a cell cannot modify the contents of other cells, it can only return a value.