VBA Evaluate function with string arguments - excel

I have this function working ( It returns the row where the text DK001 sits in the ID range)
Found = Application.Evaluate("=IF(ID=""DK001"",ROW(ID),""x"")")
I would like to feed the searchcriteria (e.g. DK001) as a string, like
Found = Application.Evaluate("=IF(ID=SearchString,ROW(ID),""x"")")
I fail in creating a string that is accepted as a search criteria. I need your help on this! What am I doing wrong?
This Evaluate function is haunting me ....
What if I now wanted to send a value (not a string) to the function?
Found = Application.Evaluate("=IF(ID=1,ROW(ID),""x"")")
The above works!
But if I want this to be a variable like
Found = Application.Evaluate("=IF(ID=MyValue,ROW(ID),""x"")")
What then?

Double " to include them as literals:
SearchString = "DK001"
Found = Application.Evaluate(""=IF(ID=""" & SearchString & """,ROW(ID),""x"")")

With stdVBA (an open source library largely maintained by myself) you can use stdLambda to accomplish this as follows:
set lambda = stdLambda.Create("if id.value = $1 then id.row else ""x""").bindGlobal("id",range("ID"))
'later...
Found = lambda("DK001")

Could you try
Application.Evaluate("=IF(ID="" & searchsrtring & "",ROW(ID),""x"")")

Related

VB.NET string.contains using wildcards

I Noticed that in a loop inside treeview items , when i am using string.contains method parallel with a textbox that i enter the search string in order to highlight finded nondes , i cant use any wildcard like * or % ... is there any other way to use wildcards ?
What i have tried is having multiple textboxes ex. textbox_x, textbox_y and multiple string.contains in the code string.contains(x) or string.contains(y) but that obviusly doesnt meet my needs because the user may want to use numerous wildcard combinations..
This is a simple function that allows the use of * as jokers at any position
(using regex, here also set to case-insensitive).
Public Shared Function TestSimplePattern(value As String, pattern As String) As Boolean
If String.IsNullOrEmpty(value) Or String.IsNullOrEmpty(pattern) Then Return False
Dim parts = pattern.Split("*")
Dim rxPattern = String.Join(".*?", parts.Select(Function(item) Regex.Escape(item)).ToArray)
rxPattern = "^" & rxPattern & "$"
Return Regex.IsMatch(value, rxPattern, RegexOptions.IgnoreCase)
End Function
Can be used like this:
TestSimplePattern("VB.NET string.contains using wildcards", "*wildcards") ' true
TestSimplePattern("VB.NET string.contains using wildcards", "*string*using*") ' true
TestSimplePattern("VB.NET string.contains using wildcards", "*string*using") ' false

Use String text as Code in Visual Basic for Excel

For various reasons, I need to concatenate a text of the form [NAME].Value by changing the value of NAME to an inputbox entry.
Something like this:
Sub example()
data_in = InputBox("Give me something: ")
mystring1 = "[" & data_in & "].Value"
a = Evaluate(mystring1) 'I know this is wrong, but I don't know how to do so.
End Sub
I know it can be done in other ways, and the example in which I want to use this code is not exactly this one, and while it can be done in several ways here, in the original code it can only be done this way.
I want, based on the input in the imputbox, to concatenate the string in whatever way, and subsequently cast that string as code to store the value in another variable, to be used later in the code.
I am not able to get VBA to read the string text as code. I have seen that there is a way that consists of creating a macro from this first macro, execute it, and then delete the recently created macro. The problem with this solution is that doing that I can't save the variable when returning to the initial macro (I don't want to use global variables).
Surely there must be a way?
Thank you very much.
EDIT: The code above returns Error 2015
In order to use a string as if it was code, you can use the evaluate function (exists in most languages)
The official documentation mentions this example:
[a1].Value = 25
Evaluate("A1").Value = 25
trigVariable = [SIN(45)]
trigVariable = Evaluate("SIN(45)")
Set firstCellInSheet = Workbooks("BOOK1.XLS").Sheets(4).[A1]
Set firstCellInSheet = _
Workbooks("BOOK1.XLS").Sheets(4).Evaluate("A1")
I have figured out the easiest way to do it, sorry for posting the question so soon.
Thanks to #Andreas for the solution. I'll write it here in case than could be useful to someone.
Sub example()
data_in = InputBox("Give me something: ")
a = Range(data_in).Value
Debug.Print a
End Sub
In the end the simplest thing is the last thing you try...

chanaging an IF and Weekday formula into a vba

I need help to change the following function into VBA code. This will be part of a larger code.
IF((WEEKDAY($B12)=7),$I12,"")
There are probably more than 5 ways to do what you want, depending on what exactly do you need. One of these ways is to build a simple custom formula like this:
Public Function changingIfAndWeekday() As Variant
Application.Volatile
If Weekday(Range("B12")) = 7 Then
changingIfAndWeekday = Range("I12")
Else
changingIfAndWeekday = ""
End If
End Function
You could also do it like so (if you want the result on cell C12):
Sheet1.range("C12").value = "=IF(Weekday(Sheet1.range("B12").value = 7),Sheet1.range("I12").value,"")
You could also do it like so (if you want the result on a variable):
Variable = "=IF(Weekday(Sheet1.range("B12").value = 7),Sheet1.range("I12").value,"")

vba strings replacing

OK Starting all over again and hopefully a bit more straight forward.
Var = 24
string = "var"
x = string
This results in
x = "var" NOT x = 24
Is it possible to retrieve the value of var, by using the string stored in string
Thank you
Aaron
I don't believe you are able to do that. As a solution you can use a collection to mimic this behaviour:
Sub TestCollection()
Dim Values As New Collection
Values.Add "24", "Var"
Values.Add "Alexander", "Name"
MsgBox Values("Var") & " " & Values("Name")
End Sub

Stack overflow when replacing ' with '' in VB 6.0

I'm looking into some legacy VB 6.0 code (an Access XP application) to solve a problem with a SQL statement by the Access app. I need to use replace single quotes with 2 single quotes for cases where a customer name has an apostrophe in the name (e.g. "Doctor's Surgery":
Replace(customerName, "'", "''")
Which will escape the single quote, so I get the valid SQL:
SELECT blah FROM blah WHERE customer = 'Doctor''s Surgery'
Unfortunately the Replace function causes an infinite loop and stack overflow, presumably because it replace function recursively converts each added quote with another 2 quotes. E.g. one quote is replaced by two, then that second quote is also replaced by two, and so on...
----------------EDIT---------------
I have noticed (thanks to posters) that the replace function used in this project is custom-written:
Public Function replace(ByVal StringToSearch As String, ByVal ToLookFor As String,
ByVal ToReplaceWith As String) As String
Dim found As Boolean
Dim position As Integer
Dim result As String
position = 0
position = InStr(StringToSearch, ToLookFor)
If position = 0 Then
found = False
replace = StringToSearch
Exit Function
Else
result = Left(StringToSearch, position - 1)
result = result & ToReplaceWith
result = result & Right(StringToSearch, Len(StringToSearch) - position - Len(ToLookFor) + 1)
result = replace(result, ToLookFor, ToReplaceWith)
End If
replace = result
End Function
Apparently, VB didn't always have a replace function of it's own. This implementation must be flawed. An going to follow folk's advice and remove it in favour of VB 6's implementation - if this doesn't work, I will write my own which works. Thanks everyone for your input!
Are you sure that it's not a proprietary implementation of the Replace function?
If so it can just be replaced by VB6's Replace.
I can't remember which version it appeared in (it wasn't in Vb3, but was in VB6) so if the original code base was vb3/4 it could be a hand coded version.
EDIT
I just saw your edit, I was Right!
Yes, you should be able to just remove that function, it'll then use the in build VB6 replace function.
We use an VB6 application that has the option of replacing ' with ` or removing them completely.
You could also walk through the letters, building a second string and inserting each ' as ''.
I just tried this in Access and it works fine (no stackoverflow):
Public Function ReplaceSingleQuote(tst As String) As String
ReplaceSingleQuote = Replace(tst, "'", "''")
End Function
Public Sub TestReplaceSingleQuote()
Debug.Print ReplaceSingleQuote("Doctor's Surgery")
End Sub

Resources