How to prevent more than one "," in a text field - vba

Does anyone know how I can prevent users from entering more than one comma in a text field using an if statement? For example:
if txtWidth.text (contains more than one ",") then
MsgBox ("Please enter only one comma.")
Else ...
What should I put in the place of the first pair of brackets? The program I am making this for is Solidworks.
I have only just started programming and some of the terms are not very clear to me. If it is explained elsewhere and I havent searched properly I apologize.
If someone could help me that would be very nice.
Thank you in advance!
Rob

You can use the InStr() function twice :
if (InStr(1,txtWidth.Value,",") > 0 ) then
if (InStr(InStr(1,txtWidth.Value,",") + 1,txtWidth.Value,",") > 0) then
MsgBox ("Please enter only one comma.")
end if
end if
See here for more info on InStr.

I think you would need some nested if statements.
Something like this:
If input = "," Then
If numcommas = 0 Then
numcommas = 0
Else
'Don't allow input of character
End If
End If
You'll need to alter this a little bit in order to use it but this should get you started, or at least give you a geneeral idea of where to go.

This is a way to do it with just one if function:
If (Len(txtWidth.text) - Len(Replace(txtWidth.text, ",", ""))) > 1 Then
'Your Message'
End If
What this code does is it compares the length of your string with the length of your string, cleaned of all commas. So Len("Test,") would give back a length of 5 while Len(Replace("Test,",",","") returns 4 and by substracting those values you get the number of commas in your string.

Related

extract airlines from flight numbers strings in excel

I have problem of extracting two-character code from the string format like:
"VA198-VA200-VA197"
I just want to get the string:
"VA-VA-VA"
Also the data I have are not just in one format, some data is like:
"DL123-DL245"
or
"DL123-VA345-HU12-OZ123"
Does anyone know how to do it fast in excel? Thanks.
With data in A1, in B1 enter the array formula:
=TEXTJOIN("",TRUE,IF(ISERR(MID(A1,ROW(INDIRECT("1:100")),1)+0),MID(A1,ROW(INDIRECT("1:100")),1),""))
NOTE:
The formula strips out all numeric characters, leaving only the alphas and the dash.
Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key. If this is done correctly, the formula will appear with curly braces around it in the Formula Bar.
There are a couple of ways you can approach this depending on how many possible segments their are in your string. If we assume your flight number is in A1:
First Segment: =LEFT(A1,2)
Second Segment: =MID(A1,FIND("-",A1)+1,2)
Third Segment: =MID(A1,FIND("-",A1,FIND("-",A1)+1)+1,2)
You could then concatenate the three expressions together and add a fourth with some conditionals. The problem is that based on your information you can have anywhere from 1 to 4 (at least) names which means you'll need a conditional:
Second Segment: =IF(ISERR(FIND("-",A1)),"",MID(A1,FIND("-",A1)+1,2))
Adding in the separators we end up with something like this for up to four segements:
=CONCATENATE(LEFT(A1,2),IF(ISERR(FIND("-",A1)),"",CONCATENATE("-",MID(A1,FIND("-",A1)+1,2))),IF(ISERR(FIND("-",A1,FIND("-",A1)+1)),"",CONCATENATE("-",MID(A1,FIND("-",A1,FIND("-",A1)+1)+1,2))),IF(ISERR(FIND("-",A1,FIND("-",A1,FIND("-",A1)+1)+1)),"",CONCATENATE("-",MID(A1,FIND("-",A1,FIND("-",A1,FIND("-",A1)+1)+1)+1,2))))
This will give you everything in one field.
Here is a VBA type answer.Assuming all strings are structured in the same way. Meaning Two letters followed by numbers and separated with "-". If one such string is A1, and you want to write the result to B1:
Sub BreakStrings()
d = Split(Range("A1"), "-")
For i = LBound(d) To UBound(d)
d(i) = Left(d(i), 2)
Next i
strg = Join(d, "-")
Range("B1") = strg
End Sub
User-defined function (UDF):
Function GetVal(cell)
With CreateObject("VBScript.RegExp")
.Global = True: .Pattern = "(\w{2})(.+?)(?=-|$)"
GetVal = .Replace(cell, "$1")
End With
End Function

adding a for loop or if statement to excel for averaging numbers

So I have a template that I am inputting data from a csv into an excel file. The data doesn't always "file the template" so to speak or there are some fields that have '0' in them. What I am trying to do is add a for loop or something of the sort to basically 'throw out' the 0's but still average the cells say BX2-BX50. I would like excel to ignore the 0's when averaging the numbers within those fields.
Any help would be greatly appreciated!
No need to over-think this. The AVERAGEIFS function should be more than sufficient.
=averageifs(BX:BX, BX:BX, "<>0")
all,
so you mean the line with "0" is not the data, is only the error line when you convert it from CSV to Excel? If so, it is better to delete those lines as you know if the 0 shows as the correct data, it should reduce the overall average. you can eliminate the error data but you cannot ignore the real to lead to wrong result.
and for delete error zero line, you can use loop:
Sub removeZero()
Dim a As Integer
a = ActiveSheet.UsedRange.Rows.Count
For i = 1 To a
If Range("B" & i) = 0 Then
Range("B" & i) = ""
End If
Next i
Columns("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub

How to remove all occurences of a substring within a string except the first one visual basic

The code so far looks like this
For i = 0 To (Len(needed) - 1)
If key.Contains(needed(i)) = False Then
key = key + needed(i)
Else
End If
Within the else I would want to remove all occurrences of the substring key(i) from key except the first one. I could do this using a flag variable within a for loop to gain the location of this and simply replace that with "" however I have the entire alphabet and 3 other characters to check for. Is there a better method to do this???
If you wanted to replace any occurrence of a string except the first one, you could get a substring representing the the string after the first one, and run the replace then.
key.Substring(key.IndexOf(key(i)) + 1).Replace(key(i), "")
Hope this helps.

VB sentence count

I am trying to write a program that will count the number of sentences in a string. I would like to better use the framework has much has possible but I really don't understand this msdn example. So could someone explain it if they understand or does someone know how to count the number of sentences in a sting accurately? I am open to all and any suggestions.
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.sentences.count.ASPX?cs-save-lang=1&cs-lang=vb#code-snippet-1
EDIT:
Ok, for anyone that has had a hard time with counting sentences (like me) here is what I have been able to come up with and I think this is has good as you can get it. So if anyone else has a idea on how to solve sentences counting let me know. But what I have and it works.
My idea is that a sentences is defined has ". or ! or ?" and followed by at least one space. So this what seems to work. (Sorry its not a fully working module because I copied it out of class I'm using).
'Period cehck
For i As Integer = 0 To _runFor
If (str(i) = _Dot And True = Char.IsWhiteSpace(str(i + 1))) Then
_sentence_count = _sentence_count + 1
End If
Next
'Question check
For i As Integer = 0 To _runFor
If (str(i) = _Question And True = Char.IsWhiteSpace(str(i + 1))) Then
_sentence_count = _sentence_count + 1
End If
Next
'Exclamation check
For i As Integer = 0 To _runFor
If (str(i) = _Exclamation And True = Char.IsWhiteSpace(str(i + 1))) Then
_sentence_count = _sentence_count + 1
End If
Next
It's not really possible to accurately count sentences programmatically. For instance, if you wrote a piece of code that just counted the number of occurrences of a period followed by a space followed by a capital letter, then it would incorrectly interpret "I gave my report to Dr. Johnson." as two sentences.

If statement with 2 possible numbers

Hey all i am probably overthinking this but how can i check the textbox for either a 655 or 699 in the first 3 numbers in the textbox?
The current code i how now works but displays an error if (im guessing) it doesnt find the other number in the textbox as well:
If Microsoft.VisualBasic.Mid(txtNumber.Text, 1, 3) <> 655 Or Microsoft.VisualBasic.Mid(txtNumber.Text, 1, 3) <> 699 Then
'ERROR
end if
What would i be doing incorrectly?
David
Like so:
If Left(txtNumber.Text, 3) = "655" OrElse Left(txtNumber.Text, 3) = "699" Then
' good?
End if
Although it looks like you might want an error if it's not either one, in which case just wrap the two test above in paran's and put a Not before them.
First, you're going to want to use Left, not Mid if it's the first 3 characters.
Second, you're checking a string against an integer.
Third, you're checking if it's not those 3 characters when I'm guessing you want to check if they are equal, so you'll want to change that, as well.
try
If Mid(txtNumber.Text, 1, 3) <> "655" And Mid(txtNumber.Text, 1, 3) <> "699" Then
'Code
End If