I want to split a string into separate chunks in VB.Net after each empty line break.
For example if I have the following single string :
Jason Smith
Steve
Mary
Harry
Larry
I want the first set of names from Jason to Mary in array(0) & the next set in array(1). So the logic should be to split at the empty line break between the 2 sets.
I tried the below code :
Dim lines As String() = nameList.Split(New String() {vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
But this just breaks every name into a separate item on the array.
First split using vbCrLf + vbCrLf to get the different sets. Then split each of those with a single vbCrLf for the values in each array.
Related
I'm trying to write a macro in VBA to split a bunch of addresses all in the same format into separate columns. So a street address column, suburb, postcode and state code column. The addresses all follow this format:
123 Fake Street, Suburbia QLD 4123
I wish I could approach this using SQL but I'm trying to keep this function inside an excel workbook where addresses would be central.
My planned approach is to write a for loop which counts the length of column D (where the addresses are stored)...so
For LngRow = 2 To Wksht.Range("D" & Wksht.Rows.Count).End(xlUp).Row
//concate/parse here//
Next
and then it would follow a standard procedure of working backwards where it would separate and write the postcode (4 digits), then the state code (an array of state codes), then the suburb (the string between the state code and the delimiting comma after the street address), and finally the street address which is whatever string is remaining after the rest has been removed and rewritten.
I figure working backwards is best since the street address changes whereas the final 3 bits of info are standard.
Is it possible to write such a macro in VBA? Especially given how SQLish it seems.
going by description in the question and assuming that the address format will remain same, here is one approach using Split
Private Sub tt()
Dim strTest As String
Dim arr1
Dim arr2
Dim arr3
Dim StreetAddress As String
Dim Postcode As String
Dim StateCode As String
Dim SubUrb As String
strTest = "123 Fake Street, Suburbia QLD 4123"
arr1 = Split(strTest, ",")
StreetAddress = arr1(0)
arr2 = Split(Trim(arr1(1)), Space(1))
Postcode = arr2(2)
StateCode = arr2(1)
SubUrb = arr2(0)
End Sub
Excel already provides functionality which could achieve what you want. The only requirement is that you save the data to the disc and open it from a existing file. The function is called Workbooks.OpenText, but be aware that it exactly sticks to the given parameters, if you give in the wrong delimiter for example it may give you wrong results in the end or won't open the file correctly splitted.
Workbooks.OpenText "filename", _
DataType:=XlTextParsingType.xlDelimited, Origin:=XlPlatform.xlWindows, _
Space:=True, TextQualifier:=XlTextQualifier.xlTextQualifierNone
This would open a Space seperated Text or CSV file and put the values into many columns, returning an Workbooks Object were further operations can unfold.
The other approach would be to read the Text Linewise and use the VBA String Split to "manually" enter them in corresponding Rows and Columns, which has the advantage that you can manipulate data and strip out characters you don't want to have into the file on the fly. If you want I could give an example for that also.
I have a table that contains spaces in its headers
First Name Last Name Average Level Degree
_________________________________________________
Mike Lowel 25
Stan Wilson 35
Papa Peterson 15
I need it to look like this
First Last Average
Name Name Level
Degree
_____________________________________________
Mike Lowel 25
Stan Wilson 35
Papa Peterson 15
Here is what I tried
Sub test()
myString = ThisWorkbook.Worksheets(1).Range("a1").Value
ThisWorkbook.Worksheets(1).Range("a1").Value = Replace(myString, " ", CHAR(10))
ThisWorkbook.Worksheets(1).Range("a1").WrapText = True
ThisWorkbook.Worksheets(1).Range("a1").EntireRow.AutoFit
myString = ThisWorkbook.Worksheets(1).Range("b1").Value
ThisWorkbook.Worksheets(1).Range("b1").Value = Replace(myString, " ", CHAR(10))
ThisWorkbook.Worksheets(1).Range("b1").WrapText = True
ThisWorkbook.Worksheets(1).Range("b1").EntireRow.AutoFit
End Sub
However, it throws an error. In addition, I am not sure how to loop over all letters. Is there any more efficient way. I need those headers to look nice: I need to get the same effect as if I click Alt+Enter. Each word should appear on a separate line
You can do this with one line of code:
Range("A1:C1").Replace " ",vblf
In the range it replaces all spaces with a VB Line Feed (Return)
I am trying to split a string with multiple characters. The string might sometimes contain a - or a /. What I have achieved is the hyphen but I am not able to search for the slash. Any thoughts on how to split the string based on both characters at once ? Once I split after - I add the value after the - to the result list as a separate index and I would like to accomplish the same for '/'.
So For example the Split string has Jet-blue, the below code will add Jet in the result list with index(0) and blue with index(1). In addition to splitting with '-' I would also like to split with '/'. Any suggestions ?
Code:
Dim result As New List(Of String)()
For Each str_get As String In Split
Dim splitStr = str_get.Split("-")
For Each str_split As String In splitStr
result.Add(str_split) ' Enter into result list
' result.TrimExcess()
Next
result.Remove("")
Next
You can either use this or this overload of the Split method.
The first one takes an array of Char:
"Hello World".Split({"e"c, "o"c}) ' Notice the c!
The second one takes an array of String and StringSplitOptions:
"Hello World".Split({"el", "o"}, StringSplitOptions.None)
I have two lines of text which have long space (more like 14-15 spaces) before the actual text. I have tried simple replace to split and merge but nothing is working. I have also tried trim and the worst thing is that ASCII gives code of 32. But nothing works. Here is the text :
your heartburn symptoms
Certain foods, such as fat, chocolate, caffeine and alcohol can aggravate heartburn symptoms 1
Certain foods
(BTW it's not like it looks it is. In my actual richtextbox, when I select the space it gets selected as one big piece of space like a tab and i have also tried replacing vbtab but no use)
What I want is :
your heartburn symptoms
Certain foods, such as fat, chocolate, caffeine and alcohol can aggravate heartburn symptoms 1
Certain foods
Believe me I have tried almost 7-8 diffferent function but now I am going mad. Some of my logic :
Dim lineArray As String() = rtfArticle.Lines
For z As Integer = 0 To lineArray.Length - 1
Dim w As String() = lineArray(z).Split(" ")
MsgBox(lineArray(z))
Dim tmp As String = ""
For Each s34 As String In w
If (s34 <> " ") Then
temp = temp & " " & s34
End If
Next
lineArray(z) = temp
Next
It completely messes up the code. Any idea about this?
You could try:
Dim lineArray As String() = rtfArticle.Lines
For z As Integer = 0 To lineArray.Length - 1
lineArray(z) = lineArray(z).Trim()
Next
MSDN for Trim() says:
Removes all leading and trailing white-space characters from the
current String object.
I am new to VB.Net 2008. I have a tricky task to resolve, it is regarding extracting characters (values) from a long string, the extracted values from the text shall be summed up and sorted by keywords, reformatted and saved into a CSV file.
It looks something like this but much longer :
UNH+RAM6957'COMPANY1BY500C10'ZEW+REQEST6957'COMPANY2SL200C20'COMPANY1SL300C10'ZEW
The values are seperated by ' .
As first step I splitted the string to make it readable, I used the function like:
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = p_EDI
aryTextFile = LineOfText.Split("'")
For i = 0 To UBound(aryTextFile)
Console.WriteLine((aryTextFile(i)))
Next i
Now the result looks like:
UNB+UNOA:1+CCP:ZEW+STE:ZEW+100901:1200+2010917283
UNH+M000001+ORDRSP:D:96A:UN:EGT102
BGM+02G::ZEW+NOMRES24364+34
DTM+Z05:0:805
DTM+137:201009011000:203
DTM+Z01:201009090400201009100400:719
RFF+AHI:GSCOMPANY1
NAD+ZSO+CCP::ZEW
NAD+ZSH+GSSTATKRAFT::ZEW
TDT+41G++70
LOC+Z11+:::TTF
LIN+1+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBNP::ZEW
LIN+2+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBPA::ZEW
So far so good:
Now I have to extract the date and time from the header:
The line looks like:
**DTM+137**:201009011000:203 should look like
DTM+137:2010.09.01-10:00:203 and store it into a 'incomming_DTM' variable for example
Now the message period would be interresting to know:
The line looke like:
**DTM+Z01**:201009090400201009100400:719 the output should look like:
DTM+Z01 2010.09.09-04:00, 2010.09.10-04:00 and store it into 'period_DTM' variable
As next step I need to parse the next lines until it reaches the KEYWORD LIN
Like:
LIN+1+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBNP::ZEW
NAD+ZSH+COMPANY1RPH N001::ZEW (P Character in word -> SELL QTY:0 KW/h)
LIN+2+23
LOC+Z11+:::TTF
QTY+Z05:0:KW1
DTM+2:201009090400201009100400:719
NAD+ZUS+GSBPA::ZEW
NAD+ZSH+COMPANY1RRH N001::ZEW (R Character in word -> BUY QTY:0 KW/h)
and store the KEYWORDS "QTY" "DTM" "NAD+ZSH" and its following Characters
into variables.
THEN I need to parse until it reaches the next LIN Keyword and store the
keywords there into vaiables again. The goal of this complicated exercise is,
to sum up values of QTY and NAD+ZSH+COMPANY1RVH and NAD+ZSH+COMPANY1RPH
If we have a closer look at the last zwo charaters in COMPANY1RRH and COMPANY1RPH
we see RH and PH, RH means buy and PH means sell.
Maybe it is possible to store BUY or SELL into a Contract vaiable for each LIN?
I need to sum up all sells and buys which where found in the string.
Every LIN marks a time period of one hour, so we have probably 24 series per
string which contains 24 LIN every LIN have a Time period, BUY or SELL keywords
and a Quantity.
Can someone please help me with this task?
As first step, storing the keywords and its follwoing characters into variables would
be a very good start. It might be very good to do that probably until the parser reaches the LIN, then store the found values into a CSV file or Array?, then parse until the next LIN and so on...
I would like to create a CSV file out of the results like: So the CSV should contain
24 records one per every hour per every LIN..
Dim csvData = Now & "," & "TRADED_QTY" & "," & DTM+Z01 & "," & "N" & "," & QTY & "," & "KWH/h" & "," & Contract
Console.WriteLine(csvData)
Creating the CSV File with True Flag -> Append data to CSV.
Dim csvFile As String = "C:\Test.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
Any ideas are highly welcome, I consider this as very complex task
espacial as I am really new to VB.NET.
Thank you in advance!
I see "EDI" in your code. If this is an EDI format, then you should have, or be able to get, some kind of EDI specification. Likely, it will be a fixed-length specification, meaning that "Value X is characters 1 to 9", "Value Y is characters 10 to 11", "Value Z is character 12", etc.
Here is one possible approach to parse out the KEYWORDS as first step:
Dim EDI As Object
EDI = dataReader(0)
'Convert EDI Object into a string and write it to the console.
Dim p_EDI As String = Convert.ToString(EDI)
'Create LineBreaks after every " ' "
Dim LineOfText As String
Dim i As Integer
Dim aryTextFile() As String
LineOfText = p_EDI
aryTextFile = LineOfText.Split("'")
'Starting with IF clause to find keywords
For Each line As String In aryTextFile
Console.WriteLine(line)
If line.StartsWith("UNB") Then
Dim foundUNB_Data = p_EDI.IndexOf("UNB")
'Start at that position and extract UNB + 27 characters
Dim UNBData = EDI.Substring(foundUNB_Data, 30)
Console.WriteLine(UNBData)
ElseIf line.StartsWith("LIN") Then
.
.
ElseIf line.StartsWith("QTY") Then
.
.
End If
Next
Any further ideas are highly welcome..
Thank you.