Basic VB troubles - vba

I'm simply wondering what symbol/character I can use to define any character in a string...
Basically I have a number of records with RR 2, RR#2, RR1, RR 1, etc. and I want to use a symbol that will define anything after the RR and replace it with nothing "". I know in SQL it's the "%" symbol, but not sure in VBA.
I am using the Replace function in ArcGIS field calculator.
I tried searching but cannot come up with the right question to find the answer I'm looking for.
Any ideas?

Since it's unclear if you want VBA or VB.Net,
Here's a VBA answer just use the ChopString function using the format shown in the Test sub:
Function ChopString(str As String, after As String, Optional caseInsensitive As Boolean = True) As String
Dim x As Long
If caseInsensitive Then
x = InStr(1, str, after, vbTextCompare)
Else
x = InStr(1, str, after, vbBinaryCompare)
End If
If x Then
str = Left(str, x + Len(after) - 1)
End If
ChopString = str
End Function
Sub Test()
Dim OriginalString As String
Dim choppedString As String
OriginalString = "1234RR this will be chopped"
choppedString = ChopString(OriginalString, "RR")
MsgBox choppedString
End Sub

Sadly the .net REPLACE() function doesn't support wildcard characters, you can use a function as described here but it's a bit long winded.

Related

Excel VBA - Call application function (left, right) by name

I would like to be able to call application functions such as left() and right() using a string variable.
The reason is that my current code works fine, but has multiple instances of left() and right() that may need to change every time I run it. I'd like to be able to only change it once ("globally") every time.
After googling, I tried CallByName and Application.Run. It seems that they only work with a custom class/macro. Is this true? Is there anything else I should look into? I don't need specific code, thank you!
You can build a custom function where you pass if you want Left or Right.
Option Explicit
Sub Test()
Debug.Print LeftRight("L", "StackOverflow", 5)
Debug.Print LeftRight("R", "StackOverflow", 8)
End Sub
Function LeftRight(sWhich As String, sValue As String, iLength As Integer) As String
Select Case sWhich
Case "L": LeftRight = Left(sValue, iLength)
Case "R": LeftRight = Right(sValue, iLength)
End Select
End Function
You just use "L" or "R" as needed. Change it once and pass as sWhich each time.
You can even use a cell reference for this and update the cell before running code.
Results
Stack
Overflow
The easiest way around this is to replace all your Left and Right calls with a generic function, e.g. instead of
x = Left("abc", 2)
say
x = LeftOrRight("abc", 2)
and then have a function
Function LeftOrRight(str As Variant, len As Long) As Variant
'Uncomment this line for Left
LeftOrRight = Left(str, len)
'Uncomment this line for Right
LeftOrRight = Right(str, len)
End Function
Then you can just change the one function as required.
You could also use SWITCH to implement Scott's idea (no error handling if string length is invalid):
Sub Test()
Debug.Print LeftRight("L", "StackOverflow", 5)
Debug.Print LeftRight("R", "StackOverflow", 8)
End Sub
Function LeftRight(sWhich As String, sValue As String, iLength As Integer) As String
LeftRight = Switch(sWhich = "L", Left$(sValue, iLength), sWhich = "R", Right$(sValue, iLength))
End Function

CountWord and CountVowel into Function in VB.NET

Hi I need to change WordCount and CountVowel procedures to functions and create a function to count number of consonants in a string.
I have done these two procedures but I cannot figure out how to do the last part. I am fairly new to programming.
My current code is given below:
Sub Main()
Dim Sentence As String
Console.WriteLine("Sentence Analysis" + vbNewLine + "")
Console.WriteLine("Enter a sentence, then press 'Enter'" + vbNewLine + "")
Sentence = Console.ReadLine()
Console.WriteLine("")
Call WordCount(Sentence)
Call VowelCount(Sentence)
Console.ReadLine()
End Sub
Sub WordCount(ByVal UserInput As String)
Dim Space As String() = UserInput.Split(" ")
Console.WriteLine("There are {0} words", Space.Length)
End Sub
Sub VowelCount(ByVal UserInput As String)
Dim i As Integer
Dim VowelNumber As Integer
Dim Vowels As String = "aeiou"
For i = 1 To Len(UserInput)
If InStr(Vowels, Mid(UserInput, i, 1)) Then
VowelNumber = VowelNumber + 1
End If
Next
Console.WriteLine("There are {0} vowels", VowelNumber)
End Sub
Thanks for your time
I would use the following three functions. Note that WordCount uses RemoveEmptyEntries avoids counting empty words when there are multiple spaces between words.
The other two functions count upper case vowels as vowels, rather than just lower case. They take advantage of the fact that strings can be treated as arrays of Char, and use the Count method to count how many of those Chars meet certain criteria.
Note that the designation of "AEIOU" as vowels may not be correct in all languages, and even in English "Y" is sometimes considered a vowel. You might also need to consider the possibility of accented letters such as "É".
Function WordCount(UserInput As String) As Integer
Return UserInput.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Length
End Function
Function VowelCount(UserInput As String) As Integer
Return UserInput.Count(Function(c) "aeiouAEIOU".Contains(c))
End Function
Function ConsonantCount(UserInput As String) As Integer
Return UserInput.Count(Function(c) Char.IsLetter(c) And Not "aeiouAEIOU".Contains(c))
End Function
To turn each of your Sub routines into a Function, you need to do three things. First, you need to change the Sub and End Sub keywords to Function and End Function, respectively. So:
Sub MyMethod(input As String)
' ...
End Sub
Becomes:
Function MyMethod(input As String)
' ...
End Function
Next, since it's a function, it needs to return a value, so your Function declaration needs to specify the type of the return value. So, the above example would become:
Function MyMethod(input As String) As Integer
' ...
End Function
Finally, the code in the function must actually specify what the return value will be. In VB.NET, that is accomplished by using the Return keyword, like this:
Function MyMethod(input As String) As Integer
Dim result As Integer
' ...
Return result
End Function
So, to apply that to your example:
Sub WordCount(ByVal UserInput As String)
Dim Space As String() = UserInput.Split(" ")
Console.WriteLine("There are {0} words", Space.Length)
End Sub
Would become:
Function WordCount(userInput As String) As Integer
Dim Space As String() = UserInput.Split(" ")
Return Space.Length
End Sub
Note, ByVal is the default, so you don't need to specify it, and parameter variables, by standard convention in .NET are supposed to be camelCase rather than PascalCase. Then, when you call the method, you can use the return value of the function like this:
Dim count As Integer = WordCount(Sentence)
Console.WriteLine("There are {0} words", count)
As far as counting consonants goes, that will be very similar to your VowelCount method, except that you would give it the list of consonants to look for instead of vowels.
You could use the Regex class. It's designed to search for substrings using patterns, and it's rather fast at it too.
Sub VowelCount(ByVal UserInput As String)
Console.WriteLine("There are {0} vowels", System.Text.RegularExpressions.Regex.Matches(UserInput, "[aeiou]", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Count.ToString())
End Sub
[aeiou] is the pattern used when performing the search. It matches any of the characters you've written inside the brackets.
Example:
http://ideone.com/LEYC30
Read more about Regex:
MSDN - .NET Framework Regular Expressions
MSDN - Regular Expression Language - Quick Reference
VB is no longer a language I use frequently but I don't think I'm going to steer you wrong even without testing this out.
Sub Main()
Dim Sentence As String
Console.WriteLine("Sentence Analysis" + vbNewLine + "")
Console.WriteLine("Enter a sentence, then press 'Enter'" + vbNewLine + "")
Sentence = Console.ReadLine()
Console.WriteLine("")
'usually it's better just let the function calculate a value and do output elsewhere
'so I've commented your original calls so you can see where they used to be
'Call WordCount(Sentence)
Console.WriteLine("There are {0} words", WordCount(Sentence))
'Call VowelCount(Sentence)
Console.WriteLine("There are {0} vowels", VowelCount(Sentence))
Console.ReadLine()
End Sub
Function WordCount(ByVal UserInput As String) As Integer
Dim Space As String() = UserInput.Split(" ")
WordCount = Space.Length
'or just shorten it to one line...
'Return UserInput.Split(" ").Length
End Function
Function VowelCount(ByVal UserInput As String) As Integer
Dim i As Integer
Dim VowelNumber As Integer
Dim Vowels As String = "aeiou"
For i = 1 To Len(UserInput)
If InStr(Vowels, Mid(UserInput, i, 1)) Then
VowelNumber = VowelNumber + 1
End If
Next
VowelCount = VowelNumber
End Function
The most obvious change between a sub and a function is changing the keywords that wrap up the procedure. For this conversation let's just say that's one good word to use for encompassing both concepts since they're very similar and many languages don't really draw such a big distinction.
For Visual Basic's purposes a function needs to return something and that's indicated by the As Integer that I added to the end of both of the function declarations (can't remember if that's the right VB terminology.) Also in VB you return a value to the caller by assigning to the name of the function (also see edit below.) So I replaced those lines that were WriteLines with appropriate assignments. Last I moved those WriteLine statements up into Main. The arguments needed to be changed to use the function return values rather than the variables they originally referenced.
Hopefully I'm not doing your homework for you!
EDIT: Visual Basic underwent a lot of changes to the language during the move to .Net back in the early 2000's. I had forgotten (or possibly not even realized) that the new preferred choice for returning a value is now more in line with languages like C#. So rather than assigning values to WordCount and VowelCount you can just use Return. One difference between the two is that a Return will cause the sub/function to exit at that point even if there is other code afterward. This might be useful inside an if...end if for example. I'm hoping this helps you learn something rather than just being confusing.
EDIT #2: Now that I see the accepted answer and re-read the question it seems there was a small part about counting consonants that got overlooked. At this point I assume this was indeed a classroom exercise and the intended answer was possibly even to derive the consonant count by using the other functions.
Here you go.
Function WordCount(ByVal UserInput As String) As Integer
Dim Space As String() = UserInput.Split(" ")
Return Space.Length
End Function
Function VowelCount(ByVal UserInput As String) As Integer
Dim i As Integer
Dim VowelNumber As Integer
Dim Vowels As String = "aeiou"
For i = 1 To Len(UserInput)
If InStr(Vowels, Mid(UserInput, i, 1)) Then
VowelNumber = VowelNumber + 1
End If
Next
Return VowelNumber
End Function
Function ConsonantCount(ByVal UserInput As String) As Integer
Dim i As Integer
Dim ConsonantNumber As Integer
Dim Consonants As String = "bcdfghjklmnpqrstvwxyz"
For i = 1 To Len(UserInput)
If InStr(Consonants, Mid(UserInput, i, 1)) Then
ConsonantNumber = ConsonantNumber + 1
End If
Next
Return ConsonantNumber
End Function

How to extract numbers UNTIL a space is reached in a string using Excel 2010?

I need to pull the code from the following string: 72381 Test 4Dx for Worms. The code is 72381 and the function that I'm using does a wonderful job of pulling ALL the numbers from a string and gives me back 723814, which pulls the 4 from the description of the code. The actual code is only the 72381. The codes are of varying length and are always followed by a space before the description begins; however there are spaces in the descriptions as well. This is the function I am using that I found from a previous search:
Function OnlyNums(sWord As String)
Dim sChar As String
Dim x As Integer
Dim sTemp As String
sTemp = ""
For x = 1 To Len(sWord)
sChar = Mid(sWord, x, 1)
If Asc(sChar) >= 48 And _
Asc(sChar) <= 57 Then
sTemp = sTemp & sChar
End If
Next
OnlyNums = Val(sTemp)
End Function
If the first character in the description part of your string is never numeric, you could use the VBA Val(string) function to return all of the numeric characters before the first non-numeric character.
Function GetNum(sWord As String)
GetNum = Val(sWord)
End Function
See the syntax of the Val(string) function for full details of it's usage.
You're looking for the find function.. Example:
or in VBA instr() and left()
Since you know the pattern is always code followed by space just use left of the string for the number of characters to the first space found using instr. Sample in immediate window above. Loop is going to be slow, and while it may validate they are numeric why bother if you know pattern is code then space?
In similar situations in C# code, I leave the loop early after finding the first instance of a space character (32). In VBA, you'd use Exit For.
You can get rid of the function altogether and use this:
split("72381 Test 4Dx for Worms"," ")(0)
This will split the string into an array using " " as the split char. Then it shows us address 0 in the array (the first element)
In the context of your function if you are dead set on using one it is this:
Function OnlyNums(sWord As String)
OnlyNums = Split(sWord, " ")(0)
End Function
While I like the simplicity of Mark's solution, you could use an efficient parser below to improve your character by character search (to cope with strings that don't start with numbers).
test
Sub test()
MsgBox StrOut("72381 Test 4Dx")
End Sub
code
Function StrOut(strIn As String)
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "^(\d+)(\s.+)$"
If .test(strIn) Then
StrOut = .Replace(strIn, "$1")
Else
StrOut = "no match"
End If
End With
End Function

How to convert a string expression to vb code?

I have a string output from user interface as below,
strFormula ="gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value"
if i write code like
dblRes=gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value
it will give result.. but since its a string i could not get result
How can I remove the double quotes from the above string and get the values entered in the grid cells to be multiplied?
I don't think there's an 'easy' way to do this, since VB.Net doesn't have an "eval()" like some other languages. However, it does support run-time compilation. Here are a couple articles which may help you:
Using .NET Languages to make your Application Scriptable (VB.Net example)
Runtime Compilation (A .NET eval statement) (C# example)
Both are intended to be a bit more robust than just executing single lines of code, allowing users to input entire textboxes of their own code for example, but should give you some direction. Both include sample projects.
Hi guys thanks for your updates.. I wrote my own function by using your concepts and some other code snippets .I am posting the result
Function generate(ByVal alg As String, ByVal intRow As Integer) As String Dim algSplit As String() = alg.Split(" "c)
For index As Int32 = 0 To algSplit.Length - 1
'algSplit(index) = algSplit(index).Replace("#"c, "Number")
If algSplit(index).Contains("[") Then
Dim i As Integer = algSplit(index).IndexOf("[")
Dim f As String = algSplit(index).Substring(i + 1, algSplit(index).IndexOf("]", i + 1) - i - 1)
Dim grdCell As Infragistics.Win.UltraWinGrid.UltraGridCell = dgExcelEstimate.Rows(intRow).Cells(f)
Dim dblVal As Double = grdCell.Value
algSplit(index) = dblVal
End If
Next
Dim result As String = String.Join("", algSplit)
'Dim dblRes As Double = Convert.ToDouble(result)
Return result
End Function
Thanks again every one.. expecting same in future

Last but one Char in vb.net String

How do I find last but one character in a vbstring
for e.g. In the string V1245-12V0 I want to return V
Don't use substring to get just one character
Dim MyString As String = "V1245-12V0"
Dim MyChar As Char = MyString(MyString.Length - 2)
Sorry it's been a while since I did VB so this may not be perfect (and is probably a mixture of C# and VB) but you get the idea:
Dim s = "V1245-12V0"
Dim lastButOneLetter = String.Empty
If s.Length > 1 Then
'Can only get the last-but-one letter from a string that is minimum 2 characters
lastButOneLetter = s.Substring(s.Length - 2, 1)
Else
'do something if string is less than 2 characters
End If
EDIT: fixed to be compilable VB.NET code.
Dim secondToLastChar As Char
secondToLastChar = Microsoft.VisualBasic.Strings.GetChar(mystring, mystring.Length - 2)
http://msdn.microsoft.com/en-us/library/4dhfexk4(VS.80).aspx
Or just remember that any string is an array of chars;
secondToLastChar = mystring(mystring.Length - 2)
If you want to get the last alpha-character in a string you could use a LINQ query such as (C#):
var d = from c in myString.ToCharArray().Reverse()
where Char.IsLetter(c)
select c;
return d.First();
string.Substring(string.Length - 2, 1);
Was it difficult?
dim mychar as string
dim yourstring as string
yourstring="V1245-12V0"
mychar=yourstring.Substring(yourstring.Length - 2, 1)
Use the Substring on the string s which contains 'V1245-12V0'
s.Substring(s.Length - 2, 1);
Here's a VB solution:
Dim text = "V1245-12V0"
Dim v = Left(Right(text, 2), 1)
You do not need to check the length of text, except for your semantics as to what you want to happen for empty (and Nothing) and single character strings.
You can have your own functions like
Function Left(ByVal str as string, byval index as integer) As String
Left=str.Substring(0,index);
End Function
Function Right(ByVal str as string, byval index as integer) As String
Right=str.Substring(str.Length-index)
End Function
And use them to get what you need.