How do I limit the values I can save? - string

I'm currently working on a Registration form where all the details of a student are save in a text file.
In one of my fields, I have a combobox list of all the school he/she can select.
I populated the combobox using a textfile.
The format of these values are for example: (code~school name) SCH001~Saint Thomas College
Question - how do I limit the values I can save?
example - I want only the school code to be saved without the name of school: SCH001
Here's how I save the fields in a text file:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
Dim firstname, lastname, email, mobile, level, currentschool, currenttrack, institution1, institution2, institution3, institution4, institution5, institution6, courses1, courses2, courses3 As String
firstname = txtFName.Text
lastname = txtLName.Text
email = txtEmail.Text
mobile = txtMobile.Text
level = cmbLevel.Text
currentschool = cmbCurrentSchool.Text
currenttrack = cmbCurrentTrack.Text
institution1 = cmbInstitution1.Text
institution2 = cmbInstitution2.Text
institution3 = cmbInstitution3.Text
institution4 = cmbInstitution4.Text
institution5 = cmbInstitution5.Text
institution6 = cmbInstitution6.Text
courses1 = cmbCourse1.Text
courses2 = cmbCourse2.Text
courses3 = cmbCourse3.Text
Using sw As StreamWriter = File.AppendText("C:\Users\jmrosales\Documents\RegistrationForm\Registered.txt")
sw.WriteLine(firstname & "~" & lastname & "~" & email & "~" & mobile & "~" & level & "~" & currentschool & "~" & currenttrack & "~" & institution1 & "~" & institution2 & "~" & institution3 & "~" & institution4 & "~" & institution5 & "~" & institution6 & "~" & courses1 & "~" & courses2 & "~" & courses3)
End Using
MsgBox("Registration Complete!")
End Sub
I hope you guys understand what i'm trying to say.
I'm just new here.

You can do this in two ways:
Using .Split()
Using .Substring()
Using .Split()
Here's what your code will look like:
currentschool = cmbCurrentSchool.Text.Split("~")
This will return two strings, "SCH001" and "Saint Thomas College".
But since you need only the Code, put (0) at the end of the code above:
currentschool = cmbCurrentSchool.Text.Split("~")(0)
Further you can add c in the above snippet like:
currentschool = cmbCurrentSchool.Text.Split("~"c)(0)
This would specify ~ is a character.
using .Substring()
This will only work if it's sure that your code will always be 6 character (3 for SCH and rest 3 for the number-code)
currentschool = cmbCurrentSchool.Text.Substring(0,6)
Here, 0 means start picking the character from 1st position and 6 means get six characters to get a new string.
Hope this helps :)

Presuming that the school code would follow exactly 6 characters as in this SCH001~Saint Thomas College, you can use Substring:
currentschool = cmbCurrentSchool.Text.Substring(0,6) '6 means 6 characters to be cut from cmbCurrentSchool to currentschool
If here currentschool stores the schoolcode.
Else, you can use Split:
currentschool = cmbCurrentSchool.Text.Split("~")(0)

The most simple answer would be to split the string at ~ and just return the part you need:
If cmbCurrentSchool.Text.Contains("~") Then 'A check to avoid possible errors.
currentschool = cmbCurrentSchool.Text.Split("~"c)(0) '0 means that we should get the first item of the array, thus "SCH001".
Else
currentschool = cmbCurrentSchool.Text
End If
cmbCurrentSchool.Text.Split("~"c) will return an array of two strings:
"SCH001~Saint Thomas College" -> {"SCH001", "Saint Thomas College"}
Documentation:
String.Split() method

Related

Excel VBA: Input box with control characters

I'm using an input box to retreieve QR-codes from reader.
Unfortunately, the parameters in the QR-code are separated by group separator characters (decimal ASCII code 29) and these characters are being omitted.
The read in string contains all the data, but I can't distinguish the single parameters anymore.
What can I do? Is there another way to read in a string WITH all the control characters?
Thank you for your help!
Without further action your inputbox result indeed gets displayed as string without (visible) Chr(29) group separators ... even though the InputBox string result still contains those characters.
Therefore you need to convert the input eventually; the following Example demonstrates possible ways:
Sub testInput()
'a) Provide for QR results
Dim qr(0 To 2) As Variant
'b) Provide for default using Chr(29) group delimiters
Dim DefaultInput
DefaultInput = "a" & Chr(29) & "b" & Chr(29) & "c" & vbNewLine
'c) Execute InputBox (and assign to first QR result)
qr(0) = "0. Visible Input: " & InputBox("Enter QR", "QR input", DefaultInput)
'd) Convert visible inputs to 2nd and 3rd QR result
qr(1) = "1. Replaced Chr(29): " & Replace(qr(0), Chr(29), ",")
qr(2) = "2. Splitted Chr(29): " & Join(Split(qr(0), Chr(29)), "|")
'e) Show all three QR results
MsgBox Join(qr, vbNewLine)
End Sub
Further hint
If you need to get the different group results separately, I'd choose the split function (without joining the 0-based 1-dimensional array elements immediately, which was only done for display in the messagebox).

Validation of a dialog box for the update of fields "Mailmerge Fillin"

I'm looking for a way to validate those dialog boxes that pop up while updating a word document via excel vba.
The type of fields that I use is MailMerge Fields type "Fillin"
WordObj.ActiveDocument.MailMerge.Fields.AddFillIn
I'd like to write in them if possible too.
Update operation
Dialog box
It is by no means clear what you're trying to achieve. When you use:
ActiveDocument.MailMerge.Fields.AddFillIn
the resulting field doesn't show up in the document until something is done to cause it to update (e.g. performing the mailmerge). If you want the field to show up, use something like:
Dim wdFld As Object
With WordObj.ActiveDocument
Set wdFld = .Fields.Add(.Range.Characters.Last, -1, "QUOTE ""Default Text""", False)
wdFld.Code.Text = "FILLIN ""Some prompt"" \d ""Default Text"" \o"
End With
Other than that, you really do need to both explain how and why you're using a FILLIN field and post the code that updates it when the mailmerge is executed. After all, the use of a FILLIN field typically means the user is supposed to both make an input and press the OK/Cancel button.
To allow the specification of different ranges, prompts and defaults, you might use something like:
Sub FILLIN(StrBkMk As String, StrPrmpt As String, StrDflt As String)
Dim wdFld As Object
Dim quote As String
quote = char(34)
With WordObj.ActiveDocument
Set wdFld = .Fields.Add(.Bookmarks(StrBkMk).Range, -1, "QUOTE " & quote & StrDflt & quote, False)
wdFld.Code.Text = "FILLIN " & StrPrmpt & " \d " & StrDflt & " \o \* MERGEFORMAT "
End With
End Sub
where 'StrBkMk' is the name of a bookmark you want to position the field at. You'd then call the above code with something like:
Call FILLIN("FILLIN1", nom_signet, nouveau_texte_signet)
Or, if you're passing multi-word strings:
Call FILLIN("FILLIN1", "" & nom_signet & "", "" & nouveau_texte_signet & "")

regex for Excel to remove all but specific symbols after a specific symbol?

I have stings like this which are addresses, e.g.:
P.O. Box 422, E-commerce park<br>Vredenberg<br><br><br>Curaçao
Adelgatan 21<br>Malmö<br><br>211 22<br>Sweden
Läntinen Pitkäkatu 35 A 15<br>Turku<br><br>20100<br>Finland
I am interested in Country only. Country always comes last after a <br> tag.
Note, that there can be several such tags preceding this last value (e.g. 1st example string).
Is there a good way to do a formula may ve along those lines:
Identify end of string
Loop a character back until one reaches ">" character
Cut everything else (including the ">" encountered)
You don't need RegEx to do this if it's always the last part of the string.
You can get it with String modifiers doing
Sub Test()
Dim str As String, str1 As String, str2 As String
Dim Countries As String
str = "P.O. Box 422, E-commerce park<br>Vredenberg<br><br><br>Curaçao"
str1 = "Adelgatan 21<br>Malmö<br><br>211 22<br>Sweden"
str2 = "La¨ntinen Pitka¨katu 35 A 15<br>Turku<br><br>20100<br>Finland"
Countries = Right(str, Len(str) - InStrRev(str, "<br>") - 3)
Countries = Countries + vbNewLine + Right(str1, Len(str1) - InStrRev(str1, "<br>") - 3)
Countries = Countries + vbNewLine + Right(str2, Len(str2) - InStrRev(str2, "<br>") - 3)
MsgBox Countries
End Sub
Obviously this will need to be updated for how your data set is stored. You can loop through the dataset and use the string modifier on each line
A formula works too. If a string in A1, write in B1:
=TRIM(RIGHT(SUBSTITUTE(A1,"<br>",REPT(" ",100)),100))
Modified using an approach taken from here:
https://exceljet.net/formula/get-last-word

How to convert part of a cell value to bold

I have the below VBA code and A and B are holding some strings. I want to concatenate these values with some other strings and store the result in a different cell, but I want only the strings in A and B to be formatted as bold and the rest as normal text.
Set A = Worksheets("Mapping").Cells(rowNumber, columnNumber)
Set B = Worksheets("Mapping").Cells(rowNumber, 3)
' E.g.: A="currency", B="Small Int"
Worksheets("TestCases").Cells(i, 2) = "Verify the column " & A & " has same Data type " & B & " in code as well as Requirement document"
Expected output:
Verify the column currency has same Data type Small Int in code as well as Requirement document
Note: The values of A and B keep changing, so we cannot use the Characters() function.
Any help will be highly appreciated.
You can use the Characters() method - you just need to keep track of the length of the substrings. Personally, I would store the static strings in variables so that I can change them later without having to recalculate the indexes by hand:
' Untested
Set A = Worksheets("Mapping").Cells(rowNumber, columnNumber)
Set B = Worksheets("Mapping").Cells(rowNumber, 3)
Dim S1 = "Verify the column "
Dim S2 = " has same Data type "
Dim S3 = " in code as well as Requirement document"
With Worksheets("TestCases").Cells(i, 2)
.Value = S1 & A & S2 & B & S3
.Characters(Len(S1), Len(A)).Font.Bold
.Characters(Len(S1)+Len(A)+Len(S2), Len(B)).Font.Bold
End With
The function to change the font style is:
[Cells/Cell range].Font.FontStyle = "Bold"
Therefore something like might work:
Worksheets("Mapping").Cells(rowNumber, columnNumber).Font.FontStyle = "Bold"
You can also make things have underlines, strikethroughs etc... I found this really helpful blog post which goes through everything you should need to know:
http://software-solutions-online.com/excel-vba-formating-cells-and-ranges/#Jump4
I think you should have searched for this information yourself... Nevertheless this is the code that you should use to convert some cell data to bold:
Worksheets("Mapping").Cells(rowNumber, columnNumber).Font.Bold = True

Help with function in string

I have a variable, emailBody, which is set to a string stored in a database. The email body is set to a string via a dlookup function.
emailBody = DLookup("emailBody", "listAdditions", "Id = " & itemType)
The string that email body is set to includes an IIf function (which includes a dlookup function). When
?emailBody is entered in the immediate window during runtime, it shows that emailBody is set to the following string:
The new commodity is" & Iif(dlookup("IsVague", "CommodityType", "Description= " & newItem)="1", "vague.", "not vague.")
However, I want the dlookup and IIf functions to be evaluated and their results stored in the string. How do I properly format the emailBody string ("the new commodity...") in my database so that the functions will be evaluated and the results stored in the emailBody variable?
Your question is a bit unclear, but if [Id] (Or [Description]) is a string, then you Dlookup must be like this:
emailBody = DLookup("emailBody", "listAdditions", "Id = '" & itemType & "'")
or
emailBody = DLookup("emailBody", "listAdditions", "Id = """ & itemType & """")
That is, your constant should be surrounded by quotes. You can either use ' (single quote) or "" (doubled double quote).
I am somewhat concerned about the value of newitem, but in general you can use Eval:
s = """The new commodity is"" & " _
& "Iif(dlookup(""IsVague"", ""CommodityType"", ""Description= "" & newItem)=""1"", ""vague."", ""not vague."")"
s2 = Eval(s)
I am not sure that this is the way to go, think about it.
So you have this exact string stored in a table field, and you want Access/VBA to evaluate it, correct?
"The new commodity is " & Iif(dlookup("IsVague", "CommodityType", "Description= " & newItem)="1", "vague.", "not vague.")
If so, try the Eval() command:
emailBody = Eval(DLookup("emailBody", "listAdditions", "Id = " & itemType))

Resources