How to search for an integer in a string [closed] - vb.net

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I'm making a program that will give you the result of a sum when the input is unstructured. Please see the following:
Input:
whats 20 + 26
Output:
46
I already know how to search for text in a string (If text.IndexOf("hello") >= 0 Then)...
I have no idea how to use the two integers for an addition equation.

Here's a quick example of how to start doing this with regular expressions. This won't be bulletproof against anything you throw at it, but it should make for a good start.
Be sure to add : Imports System.Text.RegularExpressions to your .vb file
'This string is an example input. It demonstrates that the method below
'will find the sum "2345+ 3256236" but will skip over things like
' if + .04g
' 1.23 + 4
' etc...
Dim input As String = _
"aoe%rdes 2345+ 3256236 if + .04g rcfo 8 3 . 1.23 + 4 the#r whuts"
Dim pattern As String = "\s\d+\s*\+\s*\d+(?=\s|$)"
For Each _match As Match In Regex.Matches(input, pattern)
Dim a = _match.Value.Split("+"c) 'Match extracts "2345+ 3256325"
Dim x As Integer
Dim y As Integer
If Integer.TryParse(a(0), x) AndAlso Integer.TryParse(a(1), y) Then
Console.WriteLine("Found the Sum : " & x & " + " & y)
Console.WriteLine("Sum is : " & x + y)
Else
Console.WriteLine("Match failed to parse")
End If
Next
The regular expression can be broken down as
\s '(definitely) one whitespace
\d+ 'followed by any number of integer digits
\s* 'followed by (possibly) a whitespace
\+ 'followed by (definitely) a "+"
\s* 'followed by (possibly) a whitespace
\d+ 'followed by any number of integer digits
(?=\s|$) 'followed by (definitely) either a whitespace or EOL
Read more here :
Regular Expression Language - Quick Reference
.NET Framework Regular Expressions
Regular Expressions Reference

Parse the two integers into two integer variables - we'll call them x and y. Then add their results.
Dim x as Integer
Dim y as Integer
Dim result as Integer
'parse your integers- you indicate you already know how to do this
'add the results
result = x + y
'now print out the result

Related

convert an integer variable to a string with leading zeros in VBA

For starters, there are LOTS of questions that have been asked with this topic. However all the ones I kept clicking on were in languages other than VBA and I did not understand the syntax of those languages.
When I did a google search I found this answer which seemed promising. AH FIDDLE STICKS! I just realized that answer for VB and probably explains why its not working in my VBA
Situation
I have a variable called DimScale that is an integer. I want to create a string called DimName that will start with "mm-" and be following by the integer from DimScale with leading 0s such that there are a minimum of characters after "mm-".
IF DimScale = 25
Then DimName = "mm-0025"
IF DimScale = 235
Then DimName = "mm-0235"
Note Dimscale >=1 and <= 9999
What I have tried
Dim Dimscale as Integer
Dim Dimension_Style_Name as String
String.Format("{0:0000}", DimScale)
Dimension_Style_Name = DimScale$
Dimension_Style_Name.Format("{0:0000}", DimScale)
I have read the gist too that Dimscale get converted to a string and then is sent through a loop of adding a leading zero until the length of the string equals the 4 characters in my case for the integer part.
I have also seen the case with IF statments where IF Dimscale <10 then "000"& If Dimscale <100 then "00"& etc.
Is there a way to do it like like the VB method in VBA?
maybe:
DimName = "mm-" & format(DimScale,"0000")
As per #MathieuGuindon valuable (as usual) contribution:
Format (fully-qualified VBA.Strings.Format) takes a Variant parameter, and returns a Variant - you can also use its little brother Format$, which takes a String and returns a String, eliminating implicit conversions along the way
I had a similar need to apply leading zeros ( 12 to 00012 ) to a specified range. But everything I'd found thus-far used an iterative cell-by-cell approach. I found an older but still valuable posting from SiddHarth Rout. His posting pertains to case conversion ( lower to upper case ) but I found it adapted nicely to applying leading zeros.
Here is link to SiddHarth's posting:
Convert an entire range to uppercase without looping through all the cells
Here is the adaptation for applying leading zeros to a specified range:
Sub rngLeadingZeros(rng As Range, nbrZeros As Integer)
' Add leading zeros to a specified range.
Dim strZeros As String
Dim x As Integer
'build string as required for text() function:
For x = 1 To nbrZeros
strZeros = strZeros & "0"
Next
'make sure the range is formatted as text:
rng.NumberFormat = "#"
'apply the format to the range:
rng = Evaluate("index(text(" & rng.Address & ", """ & strZeros & """),)")
End Sub
Sub testZ()
With ActiveSheet
rngLeadingZeros .Range("e3:e9"), 5
End With
End Sub

Inverse log normal distribution [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
How can I get random numbers generated by a log normal distribution in VBA?
I used
Dim upper As Double, lower As Double
' Declare 2 arrays
Dim irr(26) As Double
Dim lirr(26) As Double
' set the upper and lower band
upper = 0.125
lower = 0.02
...
lirr(i ) = WorksheetFunction.LogInv(Rand, (upper - lower), lower) + lower
However I get an error.
Option Base 1
Public Function LOGINV_SAMPLE(Optional n As Integer = 1, Optional md As Variant = 1, Optional stdv As Variant = 0) As Variant
'#Execute this as array formula i.e Cnt+Shft+Enter
Dim x(), i, p As Variant
ReDim Preserve x(n)
For i = 1 To n Step 1
Randomize
p = Rnd()
x(i) = Application.LogNorm_Inv(p, stdv, md)
Next i
LOGINV_SAMPLE = Application.Transpose(x)
End Function
This works.

VBA Count maximum occurance of a value in a row [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to write a macro that searches a specified column and counts all the cells that contain a specified string, such as character "p" and character "q" then associate this in another column i.e the total column, indicating the character which has occurred maximum number of times in the corresponding row
Have attached a sample screen shot of the same.
Does anyone have any ideas?
Thank you in advance.
Based on your additional criteria of having to exclude certain columns in the row I think it may indeed be easier to use VBA and create a user defined function that you can then enter into the cells in your spreadsheet in the same way as any other function.
I've shown my attempt below which basically checks the column of each cell in the range to ensure it has a header of "Symbol" and if so adds the value of that cell to an Array (after being converted to a number value). There is then another function that gets the mode from that array (this only works on numeric values which is why it was converted in the previous step). Finally that is converted back to a letter.
It's quite a roundabout way and there may be an easier approach but hopefully this will work for now and give you some idea's of how to create these kind of functions for yourself.
Create a new module in your VBA project and copy all 4 of the below procedures into it:
Option Explicit
Public Function MostFrequentValue(RNG As Range) As String
Dim HeaderRow As Integer
Dim a As Range
Dim arr As Variant
HeaderRow = 1 'Change this to whatever row your headers are in
For Each a In RNG.Cells
If Cells(HeaderRow, a.Column) = "Symbol" Then
If IsEmpty(arr) Then
arr = Array(ConvertLetterToNumber(a.Value))
Else
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = ConvertLetterToNumber(a.Value)
End If
End If
Next
MostFrequentValue = ConvertNumberToLetter(ArrayMode(arr))
End Function
.
Function ConvertNumberToLetter(ByVal strSource As Integer) As String
ConvertNumberToLetter = LCase(Chr(strSource + 64))
End Function
.
Function ConvertLetterToNumber(ByVal strSource As String) As Integer
Dim i As Integer
Dim strResult As String
strSource = UCase(strSource)
For i = 1 To Len(strSource)
Select Case Asc(Mid(strSource, i, 1))
Case 65 To 90:
strResult = strResult & Asc(Mid(strSource, i, 1)) - 64
Case Else
strResult = strResult & Mid(strSource, i, 1)
End Select
Next
ConvertLetterToNumber = strResult
End Function
.
Function ArrayMode(Ray As Variant) As Integer
With Application
ArrayMode = .Mode(Ray)
End With
End Function
You would then enter the function into a cell like so =MostFrequentValue("A2:C2")
P.S. This assumes that the symbol in each value in the Symbol column is a lowercase letter of the alphabet (a-z). This appears to be the case from your example
You don't need a macro. The below formula will give you what you need. The range being counted appears in the formula 3 times. You would need to adjust this for the range you want to check
=INDEX(A1:C1,MODE(MATCH(A1:C1,A1:C1,0)))
Note: this will return an error if no single character appears more times than any other. In this case you could wrap the above formula in an IFERROR function to return whatever value you would want to see when this happens.
If you have any blank cells in the row, you can use the following array formula, which adds an IF statement to test for empty cells:
=INDEX(A1:C1,MODE(IF(A1:C1<>"",MATCH(A1:C1,A1:C1,0))))
When entering this formula you will need to press Ctrl + Shift + Enter

Input sequence / Output number VB.Net

I currently have a question with an activity which I am attempting.
The question is as follows:
Steve wants to enter all his staff member's names into a system. He has the following criteria however:
Must be last names.
Must be in the correct format.
Must calculate and output the number of surnames.
The format must be as the below example:
**stevens#smith#thomas#mitchell#adams**
To summarise:
The program must input the character sequence (made up of one or more surenames)
Check that the character sequence has a valid format.
Calculate and output the number of surnames.
This is what I have done so far - however I was wondering if there were any way that I could remove the array and make the code simpler and easier to remember. Any ideas are much appreciated!
Module Module1
Sub Main()
Dim sequence As String
Dim surnamecount As Integer = 0
Dim sequencearray() As String
Console.WriteLine("Please enter a character sequence")
sequence = Console.ReadLine
If Len(sequence) >= 5 And sequence.Substring(0, 2) = "**" And sequence.Substring() Then
sequencearray = Split(sequence, "#")
sequencearray(0) = sequencearray(0).Substring(2)
sequencearray(UBound(sequencearray)) = sequencearray(UBound(sequencearray)).Substring(0, Len(sequencearray(UBound(sequencearray))) - 2)
For i As Integer = 0 To UBound(sequencearray)
Console.WriteLine(sequencearray(i))
surnamecount = surnamecount + 1
Next
Console.ReadLine()
End Sub
Thank you in advance!

VB.NET code dumper [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hello im a beginner and i need to make a tool that will dump some codes that i need from a text file.
This is how the text file looks
79nxO´.[„Ò€D JƒÚY S 4 A4B67368-30F84CD6-930CEA07-C2645CDC
lÁ°uµ¥?_2¶›]éÚ[™tiipDAe LƒÚX S 4
1E2F44FA-19F77EC4-8212CEBF-6A196C36 é9£ð÷å“™—3-šÍïiÃä{r&GŠ JƒÚW
S 4 65735EC4-415C4232-91691832-8A8BE21F!VoS
Z˜©giàë½ÓX³ÁUhÛÇÖò LƒÚV S 4
CD3B3376-4638422A-A171BB50-00D194CC Û¾A#X "|ÂÒ9þ-¶=M¬°E¾+ JƒÚU
S 4
00D1996F-7F834C0F-A7B7F798-7CA393DE!¥£à«auA¾¼¢˜•ÈÖk}®˜¤ JƒÚT
S 4 8656E931-79CC8FFE-B11B168F-FEB84D92 ?Ø7pñBŽj¦Ù\
üXáæƒÕfø JƒÚS S 4 B72C3724-880944E8-B3B4CC58-EB7EB7E7 -
0íi/è+›N -‘”rU’[p$ JƒÚR S 4
CD9A4A87-1119464B-934C46AE-A36CF157 *µË0´eb€Ò;D Y6µ»Õ£”ê JƒÚQ
S 4 BC7F993F-A87F450F-A1BCC1E6-1FC9518D
(>þЬ0®žðR®ZV[óL¨¨lŒ;ôm¤ LƒÚP S 4
A3F8CC05-BABB4DB6-97E47D7E-7428D2CA ÜÌ ðs4¸ÌÏF¦Xf=êmHšÍÄô JƒÚO
S 4 C0A2FEE7-C0264D80-A1F8705A-EEA24595
#` IÐ]dÒ"ÎÑfþ0Äõ-®"€<³= JƒÚN S 4
E4D327F0-DE664C4E-BA1644BF-F0E5221C ¿Ptô(F3Ù™°Ú¹•žÒQÁü* JƒÚM
S 4 9671B975-D90D4854-9F3FAE97-A8F24DD2
ª°®õËÛH?y[ÛvN;ÿC‹[ JƒÚL S 4
82A717AB-8A0546EE-916657E9-FA87BD44 ={ÃPHÕÔŽš„ôгÒmâ ße5½j&u JƒÚK
S 4 9BD782BF-8E684DDC-B987FD8F-EF10871F
:—w°ALR-•ÿ•àz/N.ýœv˜arÚ LƒÚJ S 4
AC87845A-B7B64B22-A293D713-C46739F0 Ô¥60‘8Ä|I'Ýc¿!\¨ÃlçÒ JƒÚI
And this is for example a code "A4B67368-30F84CD6-930CEA07-C2645CDC"
I need to grab those out the file.
You can easily parse the targeted codes using a Regular Expression:
' copy & paste your string here, be sure to escape quotes properly
Dim s As String = "INSERT YOUR STRING HERE"
Dim rx As Regex
Dim m As MatchCollection
' This Regular Expression looks for a pattern like xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx
' where the x's are A thru F or Zero thru Nine
rx = New Regex("([A-F0-9]{8}\-[A-F0-9]{8}\-[A-F0-9]{8}\-[A-F0-9]{8})", RegexOptions.IgnoreCase)
m = rx.Matches(s)
For Each item In m
System.Diagnostics.Debug.Print(item.ToString)
Next
Maybe I don't fully understand, but looks like it's groups of 8 characters separated by hyphens you seek?
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "the input you have above"
Dim pattern As String = "[A-Za-z0-9]{8}\-[A-Za-z0-9]{8}\-[A-Za-z0-9]{8}\-[A-Za-z0-9]{8}"
Dim m As Match = Regex.Match(input, pattern)
Do While m.Success
Console.WriteLine("'{0}' found at position {1}", m.Value, m.Index)
m = m.NextMatch()
Loop
End Sub
End Module
http://msdn.microsoft.com/en-us/library/0z2heewz.aspx