I mean we have vbnewline, vblf, vbcr, vbtab.
Is there vbspace?
I mean this may sound trivial. Just press the space bar button or do ""
The thing is,
Space is unseen. Code will be clearer if we put vbspace.
Also there are many kind of space. Non breaking space etc.
So is there such thing? Where can I see list of vb special characters?
You can use space():- Returns a string consisting of the specified number of spaces
Dim TestString As String
' Returns a string with 1 spaces.
TestString = Space(1)
' Returns a string with 10 spaces.
TestString = Space(10)
' Inserts 10 spaces between two strings.
TestString = "Hi" & Space(10) & "Sharen Eayrs"
No, there is not. This page lists all of the vbFoo constant values: https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.constants_fields(v=vs.110).aspx
I disagree with your notion that "code will be clearer", but if you really want:
Public Const vbSpace As String = " "
Related
so I have this check combo box data source from SQL Server
Let's say I have these string value from the combo box
ABC, DEF, GHI
What I wanted next is get those string
and make them become like this
'ABC', 'DEF', 'GHI'
I've tried combining them with "'" & comboBox.Text & "'"
but it looks like this
'ABC, DEF, GHI'
You're starting with a delimited string and you want to process each substring separately, so that means splitting, processing and joining the string. There are a number of variations on a theme that will do that. Here are a couple of examples:
Dim substrings = comboBox.Text.Split(","c)
For i = 0 To substrings.getUpperBound(0)
substrings(i) = "'" & substrings(i).Trim() & "'"
Next
Dim result = String.Join(", ", substrings)
Dim result = String.Join(", ",
comboBox.Text.
Split(","c).
Select(Function(s) $"'{s.Trim()}'"))
Note that, if you're confident that there will always be a comma and one space between substrings then you can incorporate the space into the Split and do away with the Trim:
Dim substrings = comboBox.Text.Split({", "}, StringSplitOptions.None)
For i = 0 To substrings.getUpperBound(0)
substrings(i) = "'" & substrings(i) & "'"
Next
Well, you can do it LINQ style like:
Dim res as string = String.Join(“, “, String.Split(“,”c, original).Select(Function(f) $”’{f.Trim}’”))
The process is to split the original into its component parts, remove any white space, add surrounding quotes and combine back into a single string with “, “ as a separator.
I'm trying to make a simple text converter program for my first Visual Basic program. I've already written this in Python but I'm not sure how to do it in Visual Basic.
I need the program to run through the characters of a string and once it encounters a ( to then remove the bracket and ignore the rest of the text until it encounters a ).
For Example,
"This is a (not so good) sentence",
becomes
"This is a Sentence".
Previously I did this with a for loop what looked at a character in the string, then checked if it was open. If it wasn't it would append the character to an output string to the next character or if it was it would then trigger a Boolean to true what would stop the character being appended. It would then continue to stop the future characters from being appended until it found a close bracket. At that point, it would then make the Boolean false, stop the closed bracket from being appended and move back to appending characters, unless it was another bracket.
Sorry if this description is a bit rough as I'm not the best at describing things and I'm very new to visual basic. Thanks for any help given
You can achieve this by several different methods. Here is one method using Instr. Instr returns the character position (index) of a given string in another string. You can use this to determine the bounds of where to include/exclude the string chunk.
You didn't specify if there could be multiple sections encapsulated in () so I assumed there wouldn't be. However, this is a relatively easy tweak by adding either a Do...Loop or a While... loop in the Function.
Hope it helps:
Option Explicit
Public Function removeBrackets(Source As String, Optional RemoveDoubleSpaces As Boolean = False)
Dim FirstBracket As Long
Dim SecondBracket As Long
FirstBracket = InStr(1, Source, "(")
SecondBracket = InStr(1, Source, ")")
If FirstBracket >= SecondBracket Or FirstBracket = 0 Or SecondBracket = 0 Then Exit Function
removeBrackets = Left$(Source, FirstBracket - 1) & Right$(Source, Len(Source) - SecondBracket)
If RemoveDoubleSpaces Then removeBrackets = Replace$(removeBrackets, " ", " ")
End Function
'Run this
Sub Test()
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good) sentence") ' Example given
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good) sentence", True) ' Example given, slight revision. Remove double spaces
Debug.Print "The value returned is: " & removeBrackets("This is a (not so good sentence") ' missing ending bracket
Debug.Print "The value returned is: " & removeBrackets("This is a not so good) sentence") ' missing starting bracket
Debug.Print "The value returned is: " & removeBrackets("This is a not so good sentence") ' No brackets
End Sub
I have MS Access form where the user pastes a string into a field {Vars}, and I want to reformat that string into a new field so that (a) it retains whole words, and (b) "fits" within 70 columns.
Specifically, the user will be cutting/pasting variable names from SPSS. So the string will go into the field as whole names---no spaces allowed---with line breaks between each variable. So the first bit of VBA code looks like this:
Vars = Replace(Vars, vbCrLf, " ")
which removes the line breaks. But from there, I'm stumped---ultimately I want the long string that is pasted in the Vars field to be put on consecutive multiple lines that each are no longer than 70 columns.
Any help is appreciated!
Okay, for posterity, here is a solution:
The field name on the form that captures the user input is VarList. The call to the SPSS_Syntax function below returns the list of variable names (in "Vars") that can then be used elsewhere:
Vars = SPSS_Syntax(me.VarList)
Recall that user input into Varlist comes in as each variable (word) with a line break in between each. The problem is that we want the list to be on one line (horizontal, not vertical) AND a line can be no more than 256 characters in length (I'm setting it to 70 characters below). Here's the function:
Public Function SPSS_Syntax(InputString As String)
InputString = Replace(InputString, vbNewLine, " ") 'Puts the string into one line, separated by a space.
MyLength = Len(InputString) 'Computes length of the string
If MyLength < 70 Then 'if the string is already short enough, just returns it as is.
SPSS_Syntax = InputString
Exit Function
End If
MyArray = Split(InputString, " ") 'Creates the array
Dim i As Long
For i = LBound(MyArray) To UBound(MyArray) 'for each element in the array
MyString = MyString & " " & MyArray(i) 'combines the string with a blank space in between
If Len(MyString) > 70 Then 'when the string gets to be more than 70 characters
Syntax = Syntax & " " & vbNewLine & MyString 'saves the string as a new line
MyString = "" 'erases string value for next iteration
End If
Next
SPSS_Syntax = Syntax
End Function
There's probably a better way to do it but this works. Cheers.
I would like to be able to make one or two specific words bold in my sentence when using a concatenate formula. An example is shown below.
The first sentence is using the concatenate formula. The second sentence is manually typed and formatted. Is there a way to have this formatting in the concatenate formula without having to do it manually every time?
Please note that this is just an example and I may need to use it to make a string of three consecutive words bold in a different sentence. If a general rule was provided that I can work with going forwards that would be great!
I am somewhat proficient with formulae but have never used VBA. However I suspect the solution for this problem may only be available using VBA. Please be considerate if a VBA solution is required as it'll take some time and effort for me to start-up and understand.
Thanks for your time and help.
Edit:
Public Sub ExampleConcatenate()
Dim str1 As String, str2 As String, str3 As String, str4 As String, str5 As String, str6 As String
str1 = "First string "
str2 = "Second string "
str3 = "Third string"
str4 = "Fourth string "
str5 = "Fifth string "
str6 = "Sixth string"
Range("A1").Value = str1 & str2 & str3 & str4 & str5 & str6 'concatenate strings
'format bold starts 1 character after str1 and is as long as str2
Range("A1").Characters(Start:=Len(str1) + 1, Length:=Len(str2)).Font.Bold = True
End Sub
How would I further extend the final part to make the fourth and sixth strings bold?
You cannot format individual characters in a cell text if that cell contains a formula.
Excel doesn't support that.
Workaround
The only workaround is to write that cell text as constant text (with VBA) instead of a formula (if that meets your requirement).
Then you can format individual characters with:
Range("A1").Characters(Start:=1, Length:=10).Font.Bold = True
So to partly format a string you could adjust the following example
Public Sub ExampleConcatenate()
Dim str1 As String, str2 As String, str3 As String
str1 = "First string "
str2 = "Second string "
str3 = "Third string"
Range("A1").Value = str1 & str2 & str3 'concatenate strings
'format bold starts 1 character after str1 and is as long as str2
Range("A1").Characters(Start:=Len(str1) + 1, Length:=Len(str2)).Font.Bold = True
End Sub
For more sub strings it would be easier to use an array.
Public Sub ExampleConcatenate()
Dim SubStrings As Variant
SubStrings = Array("First string ", _
"Second string ", _
"Third string ", _
"Fourth string ", _
"Fifth string ", _
"Sixth string")
Range("A1").Value = Join(SubStrings, "")
'Note array counting starts with 0 not 1 so "First string" is SubStrings(0)
'format bold starts 1 character after str1 and is as long as str2
Range("A1").Characters(Start:=Len(SubStrings(0)) + 1, Length:=Len(SubStrings(1))).Font.Bold = True
'format sub string 4
Range("A1").Characters(Start:=Len(SubStrings(0)) + Len(SubStrings(1)) + Len(SubStrings(2)) + 1, Length:=Len(SubStrings(3))).Font.Bold = True
'format sub string 6
Range("A1").Characters(Start:=Len(SubStrings(0)) + Len(SubStrings(1)) + Len(SubStrings(2)) + Len(SubStrings(3)) + Len(SubStrings(4)) + 1, Length:=Len(SubStrings(5))).Font.Bold = True
End Sub
While you cannot make text bold within a formula, you CAN make text u̲n̲d̲e̲r̲l̲i̲n̲e̲d̲. No VBA needed; the magic here is unicode special characters.
After each character that you want underlined, insert the unicode combining low line character U+0332. You can copy-paste it from that site, or use this site to apply it after each character in the text you want to print.
See the example below to apply it to an arbitrary word in a text string.
=LEFT(B2,B6)&TEXTJOIN("̲",TRUE,MID(B2,ROW(OFFSET(A1,B6,0,B7)),1))&MID(B2,B6+B7,LEN(B2))
Starting with LEFT(B2,B6) returns up until the fifth word. Similarly MID(B2,B6+B7,LEN(B2)) returns everything after the fifth word.
The real magic happens with TEXTJOIN(). This function repeats the first argument in between each element of the reference in the third argument. Notice the underline is combined with the double quote character when rendered in the equation bar. The third argument uses MID() to return the fifth word, but with each letter a separate reference so that it is combined with the combining low line character by TEXTJOIN(). Splitting the fifth word by each character is achieved by passing an array as the second argument of MID() using ROW(OFFSET()) to count from the start to the end of the fifth word.
I am trying to clean up a string from a text field that will be part of sql query.
I have created a function:
Private Function cleanStringToProperCase(dirtyString As String) As String
Dim cleanedString As String = dirtyString
'removes all but non alphanumeric characters except #, - and .'
cleanedString = Regex.Replace(cleanedString, "[^\w\.#-]", "")
'trims unecessary spaces off left and right'
cleanedString = Trim(cleanedString)
'replaces double spaces with single spaces'
cleanedString = Regex.Replace(cleanedString, " ", " ")
'converts text to upper case for first letter in each word'
cleanedString = StrConv(cleanedString, VbStrConv.ProperCase)
'return the nicely cleaned string'
Return cleanedString
End Function
But when I try to clean any text with two words, it strips ALL white space out. "daz's bike" becomes "Dazsbike". I am assuming I need to modify the following line:
cleanedString = Regex.Replace(cleanedString, "[^\w\.#-]", "")
so that it also lets single white space characters remain. Advice on how to do so is greatly received as I cannot find it on any online tutorials or on the MSDN site (http://msdn.microsoft.com/en-us/library/844skk0h(v=vs.110).aspx)
Use "[^\w\.,#\-\' ]" instead of your pattern string.
Also, I would use
Regex.Replace(cleanedString, " +", " ")
instead of
Regex.Replace(cleanedString, " ", " ")
Or, if you are not a big fan of regex...
Private Function cleanStringToProperCase(dirtyString As String) As String
'specify valid characters
Dim validChars As String = " #-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
'removes all but validChars'
Dim cleanedString As String = dirtyString.Where(Function(c) validChars.Contains(c)).ToArray
Dim myTI As Globalization.TextInfo = New Globalization.CultureInfo(Globalization.CultureInfo.CurrentCulture.Name).TextInfo
'return the nicely cleaned string'
Return myTI.ToTitleCase(cleanedString.Trim)
End Function