I have a string in this format:
>word1>longword2>longerword3>word4>anotherword5>
In VBA I am looking to extract all words between the characters >. Any guidelines will be much appreciated - words contain numbers and special characters and are not fixed in length.
Use the split function : http://msdn.microsoft.com/library/6x627e5f(v=vs.90).aspx
There is an example at the end of the link.
You need to use something like:
Dim TestArray() As String;
TestArray = Split(myString, ">")
this code will solve your problem
Dim longString as String
longString = "word1>longword2>longerword3>word4>anotherword5>"
Dim arrayString() as String
arrayString = Split(longString, ">")
Related
I have a String in VBA with this text: < History Version="1.10" Client="TestClient001" >
I want to get this TestClient001 or anything that's inside Client="xxxx"
I made this code but it's not working
Client = MID(text,FIND("Client=""",text)+1,FIND("""",text)-FIND("Client=""",text)-1)
Is there a way to specifically get the text inside Client="xxxx"?
There's no such function as Find in VBA - that's a worksheet function. The VBA equivalent is InStr, but I don't think you need to use it here.
The best tool for extracting one string from another in VBA is often Split. It takes one string and splits it into an array based on a delimiting string. The best part is that the delimiter doesn't have to be a single character - you can make it an entire string. In this case, we'd probably do well with two nested Split functions.
Client = Split(Split(text,"Client=""")(1),Chr(34))(0)
The inner Split breaks your text string where it finds "Client="". The (1) returns array element 1. Then the outer Split breaks that returned text where it finds a " character, and returns array element 0 as the final result.
For better maintainability, you may want to use constants for your delimiters as well.
Sub EnclosedTextTest()
Const csFlag1 As String = "Client="""
Const csFlag2 As String = """"
Const csSource As String = "< History Version=""1.10"" Client=""TestClient001"" >"
Dim strClient As String
strClient = Split(Split(csSource, csFlag1)(1), csFlag2)(0)
Debug.Print strClient
End Sub
However, if the Split method doesn't work for you, we can use a method similar to the one you were using, with InStr. There are a couple of options here as well.
InStr will return the position in a string that it finds a matching value. Like Split, it can be given an entire string as its delimiter; however, if you use more than one character you need to account for the fact that it will return where it finds the start of that string.
InStr(1,text,"Client=""")
will return 26, the start of the string "Client="" in the text. This is one of the places where it's helpful to have your delimiter stored in a constant.
intStart = InStr(1,text,csFlag1)+len(csFlag1)
This will return the location it finds the start of the delimiter, plus the length of the delimiter, which positions you at the beginning of the text.
If you store this position in a variable, it makes the next part easier as well. You can use that position to run a second InStr and find the next occurrence of the " character.
intEnd = InStr(intStart,text,csFlag2)
With those values, you can perform your mid. You code overall will look something like this:
Sub InstrTextTest()
Const csFlag1 As String = "Client="""
Const csFlag2 As String = """"
Const csSource As String = "< History Version=""1.10"" Client=""TestClient001"" >"
Dim strClient As String
Dim intPos(0 To 1) As Integer
intPos(0) = InStr(1, csSource, csFlag1) + Len(csFlag1)
intPos(1) = InStr(intPos(0), csSource, csFlag2)
strClient = Mid(csSource, intPos(0), intPos(1) - intPos(0))
Debug.Print strClient
End Sub
This will work, but I prefer the Split method for ease of reading and reuse.
You can make use of Split function to split at character = then with last element of the resulting array remove character quotes and > with help of replace function and you will get the required output.
In the end I got it thanks to the idea given by #alok and #Bigben
Dim cl() As String
Dim ClientCode As String
If (InStr(1, temp, "Client=", vbTextCompare) > 0) Then
cl = Split(temp, "=")
ClientCode = cl(UBound(cl))
ClientCode = Replace(ClientCode, """", "")
ClientCode = Replace(ClientCode, ">", "")
It's XML, so you could do this:
Dim sXML As String
sXML = "<History Version=""1.10"" Client=""TestClient001"">"
With CreateObject("MSXML.Domdocument")
.LoadXML Replace(sXML, ">", "/>") 'close the element
Debug.Print .FirstChild.Attributes.getnameditem("Client").Value
End With
In Excel VBA, how to replace all sub-strings of xyz(*)in a string which contains several instances of this sub-string?
* in xyz(*) means every thing in between the two parenthesis. For example the string is "COVID-19 xyz(aaa) affects xyz(bbbbbb) so much families." This changes to "COVID-19 affects so much families."
You should use a regular expression.
for example:
Sub a()
Dim Regex As New RegExp
Dim SubjectString As String
SubjectString = "COVID-19 xyz(test) affects xyz(test) so much, families."
With Regex
.Global = True
.Pattern = "(\sxyz(\S*))"
End With
Dim ResultString As String
ResultString = Regex.Replace(SubjectString, "")
MsgBox (ResultString)
End Sub
the first \s used to grab 1 whitespace before the xyz, so when you delete replace, it won't leave 2 white spaces. <br> then looking for the string xyz and the opening parenthesis, inside it I look for \S which is any char and * means 0 or more times and then I look for the closing parenthesis.
here's a solution avoiding regexp, which I tend to avoid whenever possible and convenient (as this case seems to me)
Dim s As String
s = "COVID-19 xyz(aaa) affects xyz(bbbbbb) so much families."
Dim v As Variant
For Each v In Filter(Split(s, " "), "xyz(")
s = Replace(s, v & " ", vbNullString)
Next
I got the use of Filter() from this post
Dim textstring as String,warray() as String
textstring=Range("A3").Value
warray=split(textstring,"")
If isDate(warray(0))=True Then
Range("A4").Value=warray(1)
End If
This code displays only one word, no other words are displayed.
Typically, the vba Split function is used to split a string into a multiple element array on a delimiter. If a space was used as the delimiter, a sentence or paragraph would be split into individual words.
You are providing a zero-length string (e.g. "" ) as the delimiter. From the msdn docs:
... If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
So if you want to actually split something into multiple pieces, you cannot use a zero-length string as the delimiter.
If you used a space as the delimiter and provided no other parameters, then your example would be split into four elements of the array. I suspect you only want to split off the time and leave the show title together. The limit parameter is used for this. A limit of 2 will split your original string into a time and a show title.
Option Explicit
Sub Macro3()
Dim textstring As String, warray() As String
textstring = Range("A3").Value
warray = Split(expression:=textstring, delimiter:=" ", limit:=2)
If IsDate(warray(0)) Then
Range("A4").Value = warray(0)
Range("A5").Value = warray(1)
End If
End Sub
Most people ask how to get the characters from a string, which can be done by Mid(). I am trying to assign a string character by character in VBA code. The characters to be assigned depend on some calculated results.
I do not want to use string concatenation to form the string.
I have searched the web, but the posted solution, strName.Chars(i) (e.g., at MS development network), is not recognized in my 2007 Access VBA.
Thanks
You can use Mid to set values, too.
Sub showMidExample()
Dim s As String
s = "aaaaa"
Dim i As Integer
For i = 1 To Len(s)
Mid(s, i) = "n"
Debug.Print s
Next i
End Sub
This prints out
naaaa
nnaaa
nnnaa
nnnna
nnnnn
Which is what you are looking for.
Since no working answer is posted. I assume that cannot be done in VBA and I have to use concatenation to form the string although that is cumbersome in my case.
I cannot find a solution as how to chop off part of a string(filepath) and use what's left to get another string.
For example: if I have filepath: Q:\2456_blah_blah\file.txt and I want to put this entire filepath into an array and delete from left characters 0 through 8 (which is consistent for my application) so I'd have 'blah_blah\file.txt' left for my array.
(The blah_blah portion is going to be a dynamic length, but it will always be letters.)
So then I'd like to take the 'blah_blah\file.txt' and pull just from that beginning up to the next '\' symbol, getting "blah_blah" as a string. I'm not too savy with VB strings at this point, so any help would be much appreciated. This is just my thinking how it could be done, if there's a simpler solution, I'm all ears.
Thanks,
Two Substring calls should do it.
Dim str As String = "Q:\2456_blah_blah\file.txt"
str = str.Substring(8, str.Length - 8)
Dim blah As String = str.Substring(0, str.IndexOf("\"))
Are you looking for something like this. Not knowing all the details makes it difficult to create something that fits your needs but I'll give it a shot. This will return back the blah_blah portion of your strings no matter how large "blah_blah" is, no matter how long the filename is, no matter how long the first portion of your string is and no matter how deep the path goes.
Dim test As String = "c:\34242_blah_blah\test.txt"
Dim startPos As Integer = test.IndexOf("_") + 1
Dim endPos As Integer = test.IndexOf("\", startPos)
Dim result As String = test.Substring(startPos, endPos - startPos)