vba strings replacing - string

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

Related

Extract only a specific text in excel in a machine generated chat transcript

I have a machine generated chat data exported to excel as below
User: I need help in cancelling my order
Agent: Sure I can assist you on that
User: cool
User: Also, I need your support in ordering some other item
User: I don't know how to do that
Agent: Sure, I'll help with all your queries
I'm trying to extract only the user text from the above conversation from each cell into a seperate cell in excel
I tried all known methods to the best of my knowledge to get it. Unfortunately, unable to do so. Please help me achieving this.
Sample output:
I want to extract only user typed message to a different cell from the above conversation like below
User: I need help in cancelling my order
User: cool
User: Also, I need your support in ordering some other item
User: I don't know how to do that
If VBA UDF is an option then we can use regular expressions like ...
Option Explicit
Function ExtractUserChat(ChatString As String) As String
Dim regex As Object, mc As Object, result As String, i As Long
Set regex = CreateObject("VBScript.regexp")
regex.ignorecase = False
regex.Global = True
regex.Pattern = "User: "
ChatString = regex.Replace(ChatString, "{<<USER>>: ")
'Or if you want each submatch on next line then
'ChatString = regex.Replace(ChatString, "{" & Chr(10) & "USER>>: ")
regex.Pattern = "Agent: "
ChatString = regex.Replace(ChatString, "}Agent: ") & "}"
regex.Pattern = "\{[^}]+\}"
Set mc = regex.Execute(ChatString)
result = ""
For i = 0 To mc.Count - 1
result = result & mc(i)
Next i
result = Replace(Replace(result, "{", ""), "}", "")
ExtractUserChat = result
End Function
Assuming the text string appears in a single cell, then FILTERXML might help (see here, for example).
I was able to get the desired result by using FILTERXML together with the the LET function:
=IFERROR(LET(
X, FILTERXML("<t><s>" &SUBSTITUTE($A$1, "User:", "</s><s>")&"</s></t>", "//s"),
Y, IFERROR(SEARCH("Agent:", X)-2, LEN(X)),
"User: "&LEFT(X,Y)),
"")
Working step-by-step:
FILTERXML("<t><s>" &SUBSTITUTE($A$1, "User:", "</s><s>")&"</s></t>", "//s")creates a dynamic array of the string, splitting the text into different rows whenever "User:" appears in the string.
Where X represents the value of each cell in the dynamic array generated in step 1, IFERROR(SEARCH("Agent:", X)-2, LEN(X)) returns either the position of the string "Agent:" within X or the length of X.
Using the LET function, we call step 1 X and step 2 Y. Then our output is the left-most Y characters of X, prepended with the string "User: " (to account for its removal in step 1).
We wrap the entire function in an IFERROR to maintain best practice .
Note that if you want the output in a single cell rather than multiple, you can simply join the cells together with TEXTJOIN. Something like the below would do the trick.
=TEXTJOIN(" ", 1, IFERROR(LET(
X, FILTERXML("<t><s>" &SUBSTITUTE($A$1, "User:", "</s><s>")&"</s></t>", "//s"),
Y, IFERROR(SEARCH("Agent:", X)-2, LEN(X)),
"User: "&LEFT(X,Y)),
""))

VB.net Trim function

I have an issue with trim the string method NOT working completely I have reviewed MS Docs and looked of forums but with no luck... It's probably something simple or some other parameter is missing. This is just a sample,
Please note I need to pick up text before and after #, hence than I was planning to use # as a separator. Trim start # #, Trim End # #. I can't use The last Index or Replace per my understanding they have no direction. But perhaps I am misunderstood MS docs regards to trim Start and End as well...
thanks!
Dim str As String = "this is a #string"
Dim ext As String = str.TrimEnd("#")
MsgBox(ext)
ANSWER:
I found a solution for my problem, if you experience similar please see below:
1st: Trim end will NOT scan for the "character" from the Right as I originally thought it will just remove it from the right.... A weak function I would say:). IndexOf direction ID would be a very simple and helpful. Regards My answer was answered by Andrew, thanks!
Now there is another way around it if you try to split a SINGLE String INTO - QTY based on CHARACTER separation and populate fields accordingly.
Answer is ArrayList. Array List will ID each String so you can avoid repeated populations and etc. After you can use CASE or IF to populate accordingly.
Dim arrList As New ArrayList("this is a # string".Split("#"c)) ' Will build the list of your strings
Dim index As Integer = 1 ' this will help us index the strings 1st, 2nd and etc.
For Each part In arrList 'here we are going thru the list
Select Case index ' Here we are identifying which field we are populating
Case 1 '1st string(split)
MsgBox("1 " & arrList(0) & index) '1st string value left to SPLIT arrList(0).
Case 2 '2nd string(split)
MsgBox("2 " & arrList(1) & index) '2nd string value left to SPLIT arrList(1).
End Select
index += 1 'Here we adding one shift thru strings as we go
Next
Rather than:
Dim str As String = "this is a #string"
Dim ext As String = str.TrimEnd("#")
Try:
Dim str As String = "this is a #string"
Dim ext As String = str.Replace("#", "")
Dim str As String = "this is a #string"
Dim parts = str.Split("#"c)
For Each part in parts
Console.WriteLine($"|{part}|")
Next
Output:
|this is a |
|string|
Maybe there is a better way as we know there are multiple things to do the same thing.
The solution I used is below:
Dim arrList As New ArrayList("this is a # string".Split("#"c)) ' Will build the list of your strings
Dim index As Integer = 1 ' this will help us index the strings 1st, 2nd and etc.
For Each part In arrList 'here we are going thru the list
Select Case index ' Here we are identifying which field we are populating
Case 1 '1st string(split)
MsgBox("1 " & arrList(0) & index) '1st string value left to SPLIT arrList(0).
Case 2 '2nd string(split)
MsgBox("2 " & arrList(1) & index) '2nd string value left to SPLIT arrList(1).
End Select
index += 1 'Here we adding one shift thru strings as we go
Next

How to Evaluate a Variable Value from a String?

I've been absolutely tearing my hair out over this. Is there a simple way to pull a variable value from a string? I'm trying to use this to cleanly check the value of multiple similar variables. Example:
Dim BoxString As String
For i = 1 To 100
BoxString = "response = Report" & i & "Box.value"
Application.Evaluate (BoxString)
If response = True Then
'...
End If
Next i
For context, I'm using this to evaluate which boxes on a UserForm were selected, and perform an action for each one that was.
Thanks so much in advance!

How can I pick specific string fragments out of an excel cell using a custom formula written in VBA

At work I am required to reformat incorrect Addresses on a weekly basis from records in our Salesforce instance. We gather the incorrectly formatted addresses using a Report and export them to an Excel file. My job is simply to manipulate the data in the file to format them properly then reinsert them into the database.
Typically the addresses are formatted as so:
5 Sesame Street, Anytown, Anyplace
Separating these can be done easily by hand, but I typically have to work with hundreds of addresses at a time, and using default excel formulas tends to require lots of wrangling multiple cells at once to break it up into fragments.
Thus I wrote a custom formula to run through the cell and return a specific fragment of the string based on the "Comma Number" given. So if I give a Comma Number of 1, I would get "5 Sesame Street", 2 would get me "Anytown", etc.
Here is my code so far:
Public Function fragmentAddress(address As String, numberofcommas As Integer) As String
seen = 1
lastComma = -1
Dim x As Long
Dim frag As Long
For x = 0 To Len(address)
If Mid(address, x, 1) = "," & numberofcommas = seen Then
Exit For
ElseIf Mid(address, x, 1) = "," & numberofcommas <> seen Then
seen = seen + 1
lastComma = x
End If
Next
frag = Mid(address, lastComma + 1, seen - lastComma)
fragmentAddress = frag
I have not implemented the ability to handle the final value yet, but it does not give me any outputs, only outputting a "#VALUE!" error when I attempt to give it the input
=fragmentAddress("3 Ashley Close, Charlton Kings",1)
I have some experience with programming, but this is my first time writing anything in VBA.
Any help would be appreciated, thank you.
Not exactly sure what your question is, but this is simpler:
Public Function GetAddressFragment(ByVal Address As String, ByVal Index As Integer) As String
Dim addr() As String
addr = Split(Address, ",")
On Error Resume Next
GetAddressFragment = Trim(addr(Index - 1))
End Function

VBA Evaluate function with string arguments

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"")")

Resources