How to convert textbox year date value to check if it has only 2 digits? - vb.net

The problem that I have is related to only being possible to insert 2 digit's on the field year and I was wondering if it was possible to have a string with a value 2017 and only inserting 17 when I press a button.
I have tried to use the CONTAINS property to check if it only has numbers, but now I'm kind of stuck.

You could use regex.
Private Function returnLastTwo(input As Integer) As Integer
Dim matchYearString As String = "(?:(\d\d)(?:(\d\d))?)"
Dim output As Integer
If CStr(input).Length = 4 Then
output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(2).Value
ElseIf CStr(input).Length = 2 Then
output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(1).Value
Else
Throw New Exception("Check input")
End If
Return output
End Function

You can use a string/substring concept;
Module DateSplit
Sub Main()
Dim literal As String = "2017"
Dim substring As String = literal.Substring(2)
Console.WriteLine("Substring: {0}", substring)
End Sub
End Module
I did not test this code but should output 17
Another approach would be casting your date as a string and create a char array, then you can have access to the element and convert them back to numbers if you like
Dim dateToSplit As Integer = 2017
Dim strDate As String = dateToSplit.ToString()
Dim charArr() AS Char = strDate.ToCharArray()

Assuming your user enters a date like this: 01/01/2017, into the textbox:
dim dateFromTextbox = yourTextbox.Text ' ==> 01/01/2017
dim lastTwoDigits = Right(dateFromTextbox, 2) ' ==> 17

Related

Separate a String into Two parts 'name' and 'number' using VBA

I need to separate following strings into Name and Number: e.g.
evil333 into evil and 333
bili454 into bili and 454
elvis04 into elvis and 04
Split(String, "#") ' don't work here because numbers are unknown
similarly
Mid(String, 1, String - #) ' don't work because Numbers length is unknown
so what should be the best way to start? Just want to keep it simple as possible
Update:
For further info follow - https://youtu.be/zjF7oLLgtms
Two more ways for solving this:
Sub test()
Dim sInputString As String
Dim i As Integer
Dim lFirstNumberPos As Long
sInputString = "evil333"
'loop through text in input string
'if value IsNumeric (digit), stop looping
For i = 1 To Len(sInputString)
If IsNumeric(Mid(sInputString, i, 1)) Then
lFirstNumberPos = i
Exit For
End If
Next i
Dim Name As String
Dim Number As String
'return result
Name = Left$(sInputString, lFirstNumberPos - 1)
Number = Mid$(sInputString, lFirstNumberPos)
End Sub
Or another method:
Sub test2()
'if you are going to have too long string it would maybe better to use "instr" method
Dim sInputString As String
Dim lFirstNumberPos As Long
Dim i As Integer
sInputString = "evil333"
Dim lLoopedNumber as Long
LoopedNumber = 0
lFirstNumberPos = Len(sInputString) + 1
'loop through digits 0-9 and stop when any of the digits will be found
For i = 0 To 9
LoopedNumber = InStr(1, sInputString, cstr(i), vbTextCompare)
If LoopedNumber > 0 Then
lFirstNumberPos = Application.Min(LoopedNumber,lFirstNumberPos)
End If
Next i
Dim Name As String
Dim Number As String
'return result
Name = Left$(sInputString, lFirstNumberPos - 1)
Number = Mid$(sInputString, lFirstNumberPos)
End Sub
You should regular expressions (regex) to match the two parts of your strings. The following regex describes how to match the two parts:
/([a-z]+)([0-9]+)/
Their use in VBA is thorougly explained in Portland Runner's answer to How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

get the sorted date in vb

i am writing simple program to get the sorted date . But it does not work.
Dim filepath As String = FileStr
Dim directoryPath As String = System.IO.Path.GetDirectoryName(filepath)
for Each file As String In System.IO.Directory.GetFiles(directoryPath)
Dates = {
Date.Parse(System.IO.Path.GetFileNameWithoutExtension(file))
}.ToList
Next
Dates.Sort()
ComboBox1.DataSource = Dates
It only show one date ..where there are more than 10 date. and also the loop is working
I declare the List as global
You're replacing the content of your list in every loop
Dim filepath As String = FileStr
Dim directoryPath As String = System.IO.Path.GetDirectoryName(filepath)
for Each file As String In System.IO.Directory.GetFiles(directoryPath)
Dates.Add(Date.Parse(System.IO.Path.GetFileNameWithoutExtension(file)))
Next
Dates.Sort(AddressOf SortDate)
ComboBox1.DataSource = Dates
UPDATE: Sorting issue
Then as a seperate function add:
Function SortDate(ByVal a As DateTime, ByVal b As DateTime)
Dim result As Integer = a.Year.CompareTo(b.Year)
If result = 0 Then
a.Month.CompareTo(b.Month)
If result = 0 Then
a.Day.CompareTo(b.Day)
End If
End If
Return result
End Function
Your loop replaced the value of Dates each time, so you get only one date.
Change the loop like this:
Dates = System.IO.Directory.GetFiles(directoryPath)
.Select(Function(file) Date.Parse(System.IO.Path.GetFileNameWithoutExtension(file)))
.ToList

Get Index of last active columns per Row in Excel using Open XML

How do i get the Index of the last active column in a row using Open Xml
i have this for row 1.
Dim activeCells As IEnumerable(Of DocumentFormat.OpenXml.Spreadsheet.Cell) = row.Descendants(Of DocumentFormat.OpenXml.Spreadsheet.Cell)().Where(Function(c) Not String.IsNullOrEmpty(c.InnerText))
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = activeCells.LastOrDefault()
Dim CellRef As String = cell.CellReference
This gives D1", but what i want is the index in this case "4". how do i go about this?
To convert the cell reference to a column index you could use something like the following (I've converted the code from the answer here which you've inspired me to write :)).
Private Shared Function GetColumnIndex(cellReference As String) As System.Nullable(Of Integer)
If String.IsNullOrEmpty(cellReference) Then
Return Nothing
End If
'remove digits
Dim columnReference As String = Regex.Replace(cellReference.ToUpper(), "[\d]", String.Empty)
Dim columnNumber As Integer = -1
Dim mulitplier As Integer = 1
'working from the end of the letters take the ASCII code less 64 (so A = 1, B =2...etc)
'then multiply that number by our multiplier (which starts at 1)
'multiply our multiplier by 26 as there are 26 letters
For Each c As Char In columnReference.ToCharArray().Reverse()
columnNumber += mulitplier * (CInt(c) - 64)
mulitplier = mulitplier * 26
Next
'the result is zero based so return columnnumber + 1 for a 1 based answer
'this will match Excel's COLUMN function
Return columnNumber + 1
End Function
Note: the VB might not be idiomatic as I used the Telerik Converter to convert it from C# to VB.

What code will help me check a string for at least 2 numericals characters?

Basically, I am trying to create a random password generator using VB. However I am stumped at one certain place. I do not know how to check the string to see if at least 2 numerical characters have been inserted. I thought maybe a contain would help but I can only check for one character. Can anyone help me? The code at the moment is placed below:
Dim sChars As String="qwertyuiopasdfghjklzxcvbnmMNBVCXZLKJHGFDSAPOIUYTREWQ1234567890"
Dim sPassword As String = ""
Dim iLength As Integer
Do Until iLength >= 10 And sPassword.Contains(???)
Loop
You can use the following scenario
Dim sChars As String = "qwertyuiopasdfghjklzxcvbnmMNBV1CXZLKJHGFDSAPOIUYTREWQ"
Dim output As String = New String((From c As Char In sChars Select c Where Char.IsDigit(c)).ToArray())
If output.Length >= 2 Then
MsgBox("success")
Else
MsgBox("Doesn't meet the requirement") ' for this input this message will displayed
End If
suppose the input will be
Dim sChars As String="qwertyuiopasdfghjklzxcvbnmMNBVCXZLKJHGFDSAPOIUYTREWQ1234567890" then it will display Success
You can use the below code for matching the regex expressions:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim regex As Regex = New Regex("\d{2}")
Dim match As Match = regex.Match("Dot 77 Perls")
If match.Success Then
Console.WriteLine(match.Value)
End If
End Sub
End Module
This will match for two numerical occurrences in the string and return the result. You can use the regex match in your web/console application and not execute the entire module
A little faster version than the regex approach:
Dim password As String = "somePasswordToTest24hehe6"
Dim numberCounter As Integer
Dim counterLimit As Integer = 2
Dim hasValidCountOfNumbers As Boolean
For Each ch As Char In password
If Char.IsDigit(ch) Then
numberCounter += 1
End If
If numberCounter >= counterLimit Then
hasValidCountOfNumbers = True
Exit For
End If
Next
If hasValidCountOfNumbers Then
'do probably nothing
Else
'notify that password validation failed
End If

integer to string problems

I'm trying to make a slot machine program. This procedure that I'm trying to do will assign a name to 3 randomly generated numbers. For some reason I'm getting a conversion error saying that it cant convert the integer to a string. I tried cstr() as well but the problem persisted
Sub GenerateNumbers()
Dim numbers(2) As Integer
Dim names(5) As String
Dim x As Integer
names(0) = "Cherries"
names(1) = "Oranges"
names(2) = "Plums"
names(3) = "Bells"
names(4) = "Melons"
names(5) = "Bar"
For x = 0 To 2
numbers(x) = names(CInt(Int((6 * Rnd()) + 1)))
Next x
End Sub
gives me error: conversion from string "Oranges" to type 'Integer' is not valid
The problem is that you are getting a random string from the names array and trying to assign it to numbers, which is declared as an array of integers. Of course this is not gonna work.
Apart from that, there is also the issue with out of bounds index as Eric pointed out.
Edit in response to comments:
To get the text values of those randomly generated slot machine results you just need to declare the array to store results as strings, same way as names is declared.
To be able to get the results from a separate procedure, you need to change it from Sub to Function, which is a procedure that can return a value, an array of strings in this case. Then you can call this function from your Main or any other procedure and store the returned value in a variable.
I also corrected the part with random result generation.
Module SlotMachine
Sub Main()
Dim slotResults As String()
'Get the results
slotResults = GenerateResults()
'Some further processing of results here, e.g. print results to console
For Each item In slotResults
Console.WriteLine(item)
Next
'Wait for keypress before closing the console window
Console.ReadLine()
End Sub
'Generates random results
Function GenerateResults() As String()
Dim results(2) As String
Dim names(5) As String
Dim x As Integer
names(0) = "Cherries"
names(1) = "Oranges"
names(2) = "Plums"
names(3) = "Bells"
names(4) = "Melons"
names(5) = "Bar"
Randomize()
For x = 0 To 2
results(x) = names(Int(6 * Rnd()))
Next x
Return results
End Function
End Module
Int(6 * Rnd()) will get you 0-5, if you +1, then overflow