I want to make a set of standards which the generator would have to follow but its saying
"System.InvalidCastException: 'Conversion from string "no" to type 'Boolean' is not valid.'"
Dim capitals As String
Do Until capitals = "yes" Or "no"
Console.WriteLine("do you want your password to include capitals")
capitals = Console.ReadLine
Loop
Use:
Do Until capitals = "yes" Or capitals = "no"
This is because, in programming or separates two whole statements which can come out as a Boolean at the end.
The conditions in the original code:
• `Until capitals = "yes"
• "no"
This definitely isn't what you want, you're supposed to have Until Capitals = both sides!
Related
I'm so confused in resolving this:
In VBA syntax there is this function:
If Left("abcdef",3)="abc" then
Msgbox "True"
This function is too simple but is there any way for e.g.
To have something like this
If left("abcdef",3) is in ["A".."Z"] or if left("1265avd0",2) is in [1..9]
Which mean checking if left ("abcdef",3) which is equal to "abc" is in this Interval ["A".."Z"] or checking if the left("123avd0",2) is numeric and is in the interval of [1..9]
Hope you are understading what I want to do
Can anyone Light me in doing This?
You can use the Like operator for this simple type of comparison.
Option Explicit
Option Compare Text 'for case insensitive matching
Sub dural()
Const S1 As String = "abcdef"
Const S2 As String = "1265avd0"
Debug.Print Left(S1, 3) Like "[A-Z][A-Z][A-Z]"
Debug.Print Left(S2, 2) Like "[1-9][1-9]"
End Sub
Both will return TRUE in this instance.
As pointed out by #chrisneilsen, the comparisons can be simplified to:
S1 Like "[A-Z][A-Z][A-Z]*"
S2 Like "[1-9][1-9]*"
And you can test for either with something like:
If Left(myString, 3) Like "[A-Z][A-Z][A-Z]" or _
Left(myString, 2) Like "[1-9][1-9]" then
'do something
End if
And in the simplified version:
If myString Like "[A-Z][A-Z][A-Z]*" or _
myString Like "[1-9][1-9]*" then
'do something
End if
More complex pattern matching can be done using Regular Expressions.
If you prefer to not set Option Compare then change the alpha patterns to "[A-Za-z]"
You can use Regular Expressions ("RegEx") for this.
The pattern has a non-capturing group (?:...) that can determine if the start of the string ^ contains either three letters of any case: [a-zA-Z]{3} or | two digits \d{2}.
If either criterion is met, then the MsgBox will return True, otherwise, it returns False.
Sub test()
Dim RegEx As New RegExp, testString As String
testString = "53bcko390872"
With RegEx
.Pattern = "^(?:[a-zA-Z]{3}|\d{2})"
MsgBox .test(testString) 'will prompt True/False
End With
End Sub
You can replace the MsgBox line with something useful, such as
If .test(testString) [= True] Then...
Click Here for a live demo on the regex working (optional).
Note that you will need to set a reference to Microsoft VBScript Regular Expressions x.x
I am having trouble, here is my code.
TextBox2.Text = TextBox1.Text.Replace("a" Or "A", "test")
Simply what I have failed to find a straight answer for. I want to find lowercase "a" and replace it with "test". If it finds a capital "A" I also want to replace it with "test". When I try and OR statement it throws an error. I am looking for a solution, thank you for your time.
You just can't apply and Or operator between two strings.
If you don't want to learn Regex you can concatenate infinite .replace() calls as the return value is a new string.
If you don't care of upper or lower and just want to replace the a character (eather upper and lower) you can use .toUpper() or .toLower() on the input string before passing it to .replace()
Test 1:
Dim input = "abcABC"
output = input.replace("a", "-").replace("A", "-")
Test 2:
Dim input = "abcABC"
output = input.toLower().replace("a", "-")
Test 1 will output this string: "-bc-BC"
Test 2 will output this string: "-bc-bc"
you can simply use a Regex like :
Dim rgx As New RegularExpressions.Regex("[aA]")
If rgx.IsMatch(TextBox1.Text) Then
TextBox2.Text = "test"
End If
OR use this if statement
If TextBox1.text.Contains("a") Or TextBox1.text.Contains("A") Then
TextBox2 = "test"
End If
Or just go to the official documentation of [string.replace] site
as TnTinMn suggested , same case can be found there
TextBox2.Text = TextBox1.Text.Replace("a", "test").Replace("A","test)
I've looked for similar questions regarding this with no luck. I currently have working code that looks for a specific instance of string in the email body and subject. Upon finding this string, it has userform that takes it in another direction. My intentions are to have it run through the entire email and count how many times it finds this iteration and give that a callable variable for that userform(popup). Here is my code. It comes back with an error that says "InvalidCastException" so i'm guessing this is a conversion error. Any ideas? Thanks!
Ok so I added your comments together and came up with the following. I'm getting alot of errors, as the regex.Pattern I'm assuming doesn't exist. Any ideas? Also thank you for the literature.
Dim regEx ' Create variable.
Dim numfound As Integer
regEx = New RegExp ' Create a regular expression.
'Here it tells me that the regEx.Patter doesn't exist or Pattern is a member of the regex class
regEx.Pattern = "\*#{9}\*" ' Set pattern.
regEx.IgnoreCase = True ' Set case insensitivity.
regEx.Global = True ' Set global applicability.
If regEx.Execute(mailItem.Body) Then
' Getting a "not declared" runtime what should it be declared a Integer such as Dim numfound as Object
numfound = regEx.count
End If
Did some more digging and basically I'm back where I started with an InvalidCastException,
Conversion from string "111111111
123121233
" to type 'Long' is not valid.
Basically in the body of my test email I had those two strings of numbers and it can't convert them to a string to then run through the regexp iteration. Any ideas?
Dim sBody : sBody = (mailItem.Body) Or (mailItem.Subject) 'This is where is gives me the error
Dim Search : Search = New RegExp
Search.Global = True
Search.Pattern = "\*#{9}\*"
MsgBox(Search.Execute(sBody).Count, MsgBoxStyle.OkOnly)
To get you started, if you want to use a RegExp:
(1) Start your reading here and here
(2) Demo code to give you food for thought:
>> Dim sBody : sBody = "Three instances of ###: ### and a part of ####."
>> Dim Search : Set Search = New RegExp
>> Search.Global = True
>> Search.Pattern = "#{3,3}"
>> WScript.Echo Search.Execute(sBody).Count
>>
3
>>
The easiest way to do this would be just create an instance of RegEx and use it to parse the Item.Body.
Set Search = new RegExp
Search.IgnoreCase = True
Search.Global = True
Search.Pattern = "\*#{9}\*"
If Search.Test(Item.Body) Then
'will hold how many times it has been found
numFound = Search.Count
End If
Here is a link with a bit more information on RegExp http://msdn.microsoft.com/en-us/library/ms974570.aspx
I want to be able to extract a string in between quotation marks or parenthesis etc. to a variable. For example my text might be "Hello there "Bob" ". I want to extract the text "Bob" from in between the two quotation marks and put it in the string "name" for later use. The same would be for "Hello there (Bob)". How would I go about this? Thanks.
=======EDIT======
Sorry, I worded this poorly. Ok, so lets say I have a textbox(Textbox1) and a button. If the user inputs the text: MsgBox "THIS IS MY MESSAGE" I want that when the Button is pressed, only the text THIS IS MY MESSAGE is displayed.
This is a solution very simple:
Dim sAux() As String = TextBox1.Text.Split(""""c)
Dim sResult As String = ""
If sAux.Length = 3 Then
sResult = sAux(1)
Else
' Error or something (number of quotes <> 2)
End If
There are basically three methods -- regular expressions, string.indexof and substring and finally looping over the characters one by one. I would avoid the latter as it is just reinventing the wheel. Whether to use regexs or indexof depends upon the complexity of your requirements and data. Indexof is a bit wordy but fairly straightforward and possibly just what you want in this case.
Dim str as String = "Hello there ""Bob"""
Dim startName as Integer
Dim endName as Integer
Dim name as String = ""
startName = str.IndexOf("""")
endName = str.Indexof("""", If(startName > 0, startName,0))
If (endName>startName) Then
name = str.SubString(startName, endName)
End If
If you need to do this for arbitrary symbols, then you want regexs.
What is wrong with my If condition?
If Not IsEmpty(Wrkgps_L3) And Not IsEmpty(Wrkgps_L4) Then
Wrkgps_L3L4 = Wrkgps_L3 & "," & Wrkgps_L4
End If
The Not condition doesn't seem to work. The code within the If statement gets executed even when both Wrkgps_L3 and Wrkgps_L4 are empty strings.
Update:
Wrkgps_L3 and Wrkgps_L4 are variables that contain results returned from a function. I noticed that IsEmpty(Wrkgps_L3) = False even though Wrkgps_L3 = "". I had to rewrite my code to
If (Wrkgps_L3 <> "") And (Wrkgps_L4 <> "") Then
In any case, I am still intrigued to know why IsEmpty doesn't work on variables with ""?
In Visual Basic, Empty and "" (an empty string) are two different things. Empty is the uninitialized state of a Variant variable, and IsEmpty tests whether a Variant variable has the Empty value:
Dim x As Variant
If IsEmpty(x) Then
Debug.Print "x is empty"
End If
As you've observed, you must compare against "" when checking whether a String variable contains an empty string.
If the variables are strings, you could also:
If Len(Wrkgps_L3) + Len(Wrkgps_L4) = 0 Then
' They're both empty string variables
Else
' One or the other contains at least one character
End If