Date Format in a textbox - vb.net

Can someone help me to format this.
in my textbox (The date is 10222012)
the output should be (The date is 10/22/2012)
the text should be still there
thank you

A couple of approaches off the top of my head.
If the text is coming from one variable, for example:
Dim MyText As String = "The date is 10222012"
Then you can use String functions to get the date (assuming it is always 8 characters, which can be a dangerous assumption), format it and stick it back in:
Dim MyDate As String = CType(MyText.Substring(MyText.Length - 8), DateTime).ToString("MM/dd/yyyy")
MyText = MyText.Substring(0, MyText.Length - 8) & MyDate
If on the other hand the date is in a separate variable, say a DateTime variable, you can do this:
Dim MyDateFormatted As String = MyDate.ToString("MM/dd/yyyy")
There are other ways to do this. The key here is to get the date and convert it to the format you want via the DateTime.ToString Method (String) method, where the format string in the parantheses tells what format to use.
EDITED
That's what I get for not trying the code out first...if the string "10222012" isn't recognized as a valid format, there's another way to do this:
Dim MyText As String = dRecord.Rows(i).Item(iCount).ToString
Dim MyDate As String = MyText.Substring(MyText.Length - 8)
MyDate = MyDate.SubString(0, 2) & "/" & MyDate.Substring(2, 2) & "/" & _
MyDate.Substring(4)
oSheet.Cells(x, iCount - 2) = MyText.Substring(0, _
dRecord.Rows(i).Item(iCount).Length - 8) & _
MyDate
It's a bit more brute force and ugly, but that should get you going in the right direction. You might be able to get the same result use Insert (another String operator), but that might be just as ugly.
If you need to do this conversion a lot, I recommend putting it into a helper method, or better yet an extension method.
2nd Edit
You can check for blank record easily enough:
Dim MyText As String = dRecord.Rows(i).Item(iCount).ToString
If Not String.IsNullOrEmpty(MyText) Then
' convert the format here
End If

Related

Convert DD-MM-YY to DD-MM-YYYY using sub/function

I have been given a list of enrollment dates for some sources for an assignment.
They want me to change the dates using vba
The question is:
"As with the previous assignment that the Director gave you, the enrollment date is in a “not normal” format. The director wants the date changed into the “normal” Danish format “DD-MM-YYYY”. You, therefore, must create a sub/function that changes the date in the field to the “correct” format. As the function needs to be able to run multiple times you should use the appropriate selection statements to check that the date is in the “not normal” format before converting it."
I have attached a picture of the excel
This function appends a 20 before the year part if its only 2 characters.
Function DateConvert(BtVal dt As String) As String
Dim parts As String()
parts = Split(dt, "-")
dd = parts(1)
mm = parts(2)
yy = parts(3)
DateConvert = dd & "-" & mm & "-" & IIf (Len(yy) = 2, "20" & yy, yy)
End Function
You might want to extend this logic, for example "65" can be replaced with "1965" instead of "2065", but I leave that part to you.
The function will test whether the string matches the pattern. If it does, it returns formatted date, otherwise it returns same cell's value.
Function GetDate(cell)
With CreateObject("VBScript.RegExp")
.Pattern = "^(\d{2})-(\d{2})-(\d{2})$"
With .Execute(cell)
If .Count > 0 Then
With .Item(0)
GetDate = Format(DateSerial(.SubMatches(2), .SubMatches(1), .SubMatches(0)), "dd-MM-yyyy")
End With
Else
GetDate = cell
End If
End With
End With
End Function

Get text between \ and \PARTS from file name string vb.net

I need to obtain a value of everything between \ & \PARTS
Example:
`XamoutOFdirectorys\THIS IS WHAT I WANT\PARTS`
resulting in the text, THIS IS WHAT I WANT
in dir1\dir2\THIS IS WHAT I WANT\PARTS
I want the text THIS IS WHAT I WANT and not dir2\THIS IS WHAT I WANT
How can I achive that?
The reason is that I need to know what the files name is that is found before the PARTS directory, regardless of howmany directorys are found before and after...
the closest i can achive is ...
Dim text As String = "fat\dir1\dir2\PARTS\bat"
Dim str As String = text.Split("\"c, "\PARTS"c)(1)
MsgBox(str)
Dim str As String = "fat\dir1\dir2\PARTS\bat"
Dim dir As Match = Regex.Match(str, "\\([A-Za-z0-9\-]+)\\PARTS")
MsgBox(dir.Groups(1).ToString)
Try this
It should return an array with each text between "\". Then you can search for the text "PARTS" and take the previous index.
Split -> [dir1, dir2, your text, PARTS]
index of PARTS = 3
index of your text = 2
I don't really know vb.net but that's how I would do it with any other language.
If your path variable type is String. You can find "\PARTS" in path, get the start index A in path. Then find another index B of last "\" before A. Using substring function to get what you want between range [B, A] in path variable:
Dim str As String = "fat\dir1\XamoutOFdirectorys\_THIS IS WHAT I WANT\PARTS\bat"
Dim beginIdx, endIdx As Integer
endIdx = str.LastIndexOf("\PARTS") - 1
beginIdx = str.LastIndexOf("\", endIdx - 1) + 1
Dim result = str.Substring(beginIdx, endIdx - beginIdx + 1)
By the way, there are more elegant methods such as regular expression. But I really advice you should read MSDN about String, dirt your hand, get the solution by yourself. There are also many solution about "split path" in Stack Overflow that you can change them after you understand the solution. Best regards.
regular expression like this:
Dim str As String = "fat\dir1\XamoutOFdirectorys\_THIS IS REALLY WHAT YOU WANT.&%+\PARTS"
Dim dir As Match = Regex.Match(str, "\\([^\\]+)\\PARTS")
MsgBox(dir.Groups(1).ToString)
Which can work in real world and support all possible path versions(tested in windows system).
And the state machine illustration of my regular expression
\\([^\\]+)\\PARTS
[Debuggex Demo](https://www.debuggex.com/r/rYms5zrhWCby_FdP

VBA - Converting a mixed row ( Data Type wise) to Date

I have an excel sheet, one of the columns is mixed with Dates and Dates that has been copied to it as text ( see below ).
I dont manage to convert the text type to Date type, i need to do it though VBA to add it to some automation im working on. is there a way to do this at all ?
I noticed excel is looking for format like this 03/09/2016 23:39:57 and it doesn't like 3/21/16 11:07:22 PM, apparently this is my case :) every look i run i get ( obviously data mismatch ), in the image bellow the spoken column is "C"
thx :)
ExcelSheet bad Date format
Assuming wvery bad dates are MM/DD/YYYY, then you could use the following code that I wrote for you:
Sub main()
Dim celda As Range
Dim s_date As String
Dim s_time As String
Dim validate_date As String
Dim valid_date As String
Dim date_arr() As String
Dim rango As Range
Dim limit As Long
limit = Columns("B").Find("", Cells(Rows.Count, "B")).Row - 1
Set rango = ActiveSheet.Range("B2:B" & limit)
' works only for date values, another value would return non expected values
For Each celda In rango
validate_date = Left(celda.Value, 1)
If validate_date <> "" Then
If Not celda.Rows.Hidden Then
If validate_date <> "0" Then
s_date = Trim(Mid(celda.Value, 1, InStr(1, celda.Value, " ") - 1))
s_time = Trim(Mid(celda.Value, InStr(1, celda.Value, " "), Len(celda.Value) - InStr(1, celda.Value, " ")))
date_arr = Split(s_date, "/")
valid_date = date_arr(1)
valid_date = valid_date & "/0" & date_arr(0)
valid_date = valid_date & "/" & date_arr(2)
valid_date = valid_date & " " & s_time
celda.Offset(0, 1).Value = CDate(valid_date)
End If
End If
End If
Next celda
End Sub
In order to use this code you should insert one empty column to the right from target. Second, you should to select entire C column and run the macro.
Edit 1. Ok, this macro autoselect column B. Select column dates is not necessary now.
Excel has parsed the dates according to your Windows Regional Settings short date format. Those that it could not parse (where the month>12) it left as text. Since there was initially a difference between the date format in the text file, and the date format in your Windows Regional settings, it is likely that many of the dates that appear as dates (or as unformatted numbers) were converted incorrectly.
You have a few options:
Import the text file using the Get External Data tab From Text option on the Data Ribbon. This will open up the text import wizard and allow you to specify the date format of the data being imported.
Change your Windows Regional settings short date format to match that in the text file.
Those are probably the two simplest options. The first can be automated through VBA. The second, not so much.

using IndexOf in Mid function

Perhaps this is a simple solution for most, but I can't get this to work like it should according to syntax.
I have this line of text "Part Number123456Price$50.00"
I want to pull the part number out of it, so I use this function...
str = Mid(str, str.IndexOf("Part Number") + 12, str.IndexOf("Price"))
My results are str = "123456Price$50.0" every time. I know the part number can vary in length so I need a solid solution of pulling this out.
It can be confusing to mix the legacy VB string methods (such as Mid) with the .Net string methods (like IndexOf). The VB methods use 1 as the index of the first character while the .Net methods use 0.
The following code will extract the part number from a string
Dim str As String = "Part Number123456Price$50.00"
Dim iPart As Integer = str.IndexOf("Part Number") + 11
Dim iPrice As Integer = str.IndexOf("Price")
str = str.Substring(iPart, iPrice - iPart).Trim
The Mid() function of Visual Basic is documented as having three arguments: (1) a string, (2) the beginning location in the string, and (3) the number of characters to copy.
So if your string is "Part Number123456Price$50.00" and you want to pull the part number as a series of digits, the "123456" part of the string, using the Mid() function then you need to find the beginning of the part number digit string and to then know the number of digits.
If your string is in the variable str then you can find the offset by something like str.IndexOf("Number") + len("Number") which will provide the offset to after the string "Number".
Next you need to find the number of digits so you would do something like str.IndexOf("Price") to find where the text "Price" begins and then subtract from that offset the offset of where the digits begin.
The result of all of this is you need a bit of code something like the following. I have not tested this source as I am not a VB programmer so it may need a tweak and you might want to put some checks on data validity as well.
Dim TextNumber as String = "Number"
Dim TextPrice as String = "Price"
iOffset = str.IndexOf(TextNumber) + len(TextNumber)
str = Mid(str, iOffset, str.IndexOf(TextPrice) - iOffset)
Alternatively, if Price is always the format $00.00, this will also work.
Dim str as String = "Part Number123456Price$50.00"
str = str.Remove(str.IndexOf("Price"))

Return the ISO code from a currency formatted cell

The user, through a userform, can insert a numeric value (say 1,000,000) and an ISO code (say USD). When he will validate, the value will be printed in range A1 and will be formatted as currency through the use of the following macro-recorded line of code:
.Range("A1").NumberFormat = _
"_-[$" & Me.ISOTextBox.Value & "] * #,##0.00_-;-[$" & Me.ISOTextBox.Value & "] * #,##0.00_-;_-[$" & Me.ISOTextBox & "] * ""-""??_-;_-#_-"
Basically, the above is the string to assign the .NumberFormat property; in the case of "USD", for example, the string will look like:
"_-[$USD] * #,##0.00_-;-[$USD] * #,##0.00_-;_-[$USD] * ""-""??_-;_-#_-"
My question is: if with the above string I set the number format, how could I get it?
I could clearly make string parsing, and this is the currently "horrible" solution I'm adopting for extracting the 3-letters ISO code:
ISOcode = Left(Replace(Split(Range("A1").NumberFormat, "[")(1), "$", ""), 3)
Note: the above code is splitting the all NumberFormat by [, hence taking the second element (starting with $USD), replacing the $ with "" and taking the first three letters, standing to the standard of ISO codes that are always 3-letters long).
Documentations are very poor on this: does anyone know if there's a way of properly get the ISO code from the currency format (without turning into an unelegant string parsing)?
I'm pretty sure you will need to parse the string, but the ISO code can be extracted slightly more cleanly using:
If InStr(Range("A1").NumberFormat, "[$") <> 0 Then _
ISOcode = Mid(Range("A1").NumberFormat, InStr(Range("A1").NumberFormat, "[$") + 2, 3)