VBA insert vbNewLine in the first blank character - vba

I need to insert a vbNewLine in a cell string value after the first blank character encountered after the 50 first characters?
For example:
"At company employees with the right skills have good prospects to be promoted then a relevant position becomes available" should become
"At company employees with the right skills (vbNewLine)
have good prospects to be promoted then a relevant position becomes available"

The Replace function can start at a certain point and replace a single occurrance of a character using parameters that are usually left to defaults.
Dim str As String, i As Long
i = 50
str = "At company employees with the right skills have good prospects to be promoted then a relevant position becomes available"
str = Left(str, i - 1) & Replace(str, Chr(32), Chr(10), _
Start:=i, Count:=1)
Debug.Print str
Use 50 as the starting point, the result I receive is,
At company employees with the right skills have good
prospects to be promoted then a relevant position becomes available

Since your question is so nicely posed, here's a solution
Sub solution()
Dim test As String
Dim pos As Integer
test = "At company employees with the right skills have good prospects to be promoted then a relevant position becomes available"
pos = InStr(51, test, " ") 'search for a space on or after the 51st character
If (pos >= 51) Then
'found a space
test = Left(test, pos) & vbNewLine & Mid(test, pos + 1) 'miss out that space
End If
Debug.Print test
End Sub

Related

Combination of specific letters in many words

I have a database with a table called "sales person" which has a combination of names & surnames. On my report it must include the shortened name. Just the most left character of the Names and Surname combined. For example some has just one Name and a Surname, eg. "Pete Sampras". Combined it would show "PS" on my report. Some have more, like "Pete Steff Sampras". Combined it would be "PSS". For my own name is Johan vd Westhuizen. It must now look like "JVW". How would I go about it?
I am a beginner at this, and I'm not sure what to use. I have tried left(), but that's only for the first name
You can split the word in the spaces, and then use the Left() function to get the first character for each word.
In addition, convert it to upper case and trim to remove any spaces (I don't expect any but just in case).
See an example:
Public Function GetInitialsFromName(ByVal fullname As String) As String
'Array to hold the words
Dim arr As Variant
arr = Split(fullname, " ")
Dim initials As String, idx As Integer
'Loop each word, take the 1st letter and append it to the initials.
'Trim and convert to upper case.
For idx = LBound(arr) To UBound(arr)
initials = initials & StrConv(Left(Trim(arr(idx)), 1), vbUpperCase)
Next
GetInitialsFromName = initials
End Function
To call it:
Debug.Print GetInitialsFromName("Johan vd Westhuizen")
Debug.Print GetInitialsFromName("Pete Steff Sampras")
Debug.Print GetInitialsFromName("Pete Sampras")
'JVW
'PSS
'PS

Pad single-digit numbers with a zero

I have a loop like this to save sheets as CSV files but my first 9 sheets are name liked sinani-01 ... sinani-09 (not like sinani-1 ... sinani-9). How I can concatenate a 0 only before numbers less than 10?
Sub Adder()
Dim animal As String
Dim i As Integer
For i = 1 To 120
animal = "sinani-" & i
Sheets(animal).SaveAs "E:\Data\CSV\" & animal & ".csv", xlCSV
Next i
End Sub
VBA has a Format() function that you can use to pad numbers.
animal = "sinani-" & Format$(i, "00")
This will pad single-digit numbers with a 0. Your two- and three-digit numbers will continue to work as expected.
In the fifth line use the Format function like this:
animal = "sinani-" & Format(i, "#00")
The # means optionally a digit (i.e. present only if there are that many digits in i), 0 means definitely a digit, whereby leading zeros are used if i hasn't got enough digits.
Concatenate with a leading series of zeroes and peel off as many digits from the right-hand side as you need.
animal = "sinani-" & Right("00" & i, 2)
'alternate for many leading zeroes (e.g. DUNS number)
animal = "sinani-" & Right(String(9, "0") & i, 9)
Replace & i by & IIF(i < 10,"0","") & i
On edit: Even though in this case Format provides a cleaner solution than IIF, the IIF trick has some other uses in tweaking output. For example, if you wanted to inform the user how many cells were found which satisfy some condition you could use something like
MsgBox n & "cell" & IIF(n <> 1,"s","") & " found"
to gracefully handle plural vs. singular endings

MS Access multi field search with empty fields or multiple selections from list boxes

can some one kindly help me with MS Access? My problem is similar to the one in the following link:
MS Access multi field search with empty fields
but in my case, each search field is a list box from which we can select multiple things.
In my case, the user of the database application will enter start date and end date (text boxes) which will populate the list boxes (cost center, item number, employee id) from a single database table matching the rows that have effective date falling between start date and end date. After populating the list boxes, the user has the choice to either select multiple cost centers or leave the search field blank, multiple item numbers or blank, multiple employee numbers or blank. After selecting, if the command button display results is pressed, we should be able to get the results which satisfy all these search criteria. For example, if I select cost centers 1301, 1302 and employee no.s 492128, 492690, 492959 and leave the item numbers search field blank, then in the data table, all the entries that match these cost centers and employee no.s (all the search fields are separate columns) which fall between the start date and end date should be displayed.
I am unable to get the logic in VB. Please guide me through.
You'll need to build up an sql statement in vba then run it using a recordset, to get the results back.
Obviously I dont know what the data you'll need to get is, or from the tables you;ll get it from, however the where clause needs to be built as follows:
dim wc as string
wc = wc & iif(lst_costcenter.ItemsSelected.Count = 0, "", " AND " & InClause(lst_costcenter, "tablename.columnname", false))
wc = wc & iif(lst_itemnumber.ItemsSelected.Count = 0, "", " AND " & InClause( ...
Finally when building the sql statement, you'll need to chop of the first "AND" in wc & replace it with "WHERE"
wc = iif(wc <> "", " WHERE " & mid(trim(wc), 5), "")
InClause is a function that you need to add in a module, or in the enquiry form itself:
It uses 3 arguments:
1. The listbox control to build an in clause for,
2. A string comprising tablename-dot-columnname being the table/column to be filtered for the values selected in the listbox, &
3. True/False according to whether the datatype of the column is string (true) or numeric (false)
Public Function InClause(lst as ListBox, tblcol as string, isAlpha as boolean)
Dim si As String
Dim vv As Variant
For Each vv In lstBox.ItemsSelected
If isAlpha Then
si = si & "," & Chr(34) & lstBox.Column(0, vv) & Chr(34)
Else
si = si & "," & lstBox.Column(0, vv)
End If
Next vv
If si <> "" Then
si = "(" & tblcol & " IN (" & mid(si, 2) & "))"
End If
InClause = si
End Function
Hope this helps

Replacing space in text from a web-page

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.

EDIFACT How to group, spilt, sort and sum up values from a EDI string into variables in VB.NET

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.