Using Now() for Foreign Countries - vb.net

I'm trying to convert different date formats into an appropriate SQL DateTime format and am getting errors.
I have a client's machine that is setup with the following date format, "dd-mm-yyyy" (Localization is India)
When using Now() within VB.Net it parses the month and days backwards. I've tried the following code but get conversion errors.
Dim Month As String = Nothing
Dim Year As String = Nothing
Dim Day As String = Nothing
Dim Hour As String = Nothing
Dim Minute As String = Nothing
Dim Second As String = Nothing
Dim strDate As String = Nothing
Dim Date_to_SQL_DateTime As Date
Month = DatePart(DateInterval.Month, Now()).ToString
Year = DatePart(DateInterval.Year, Now())
Day = DatePart(DateInterval.Day, Now())
Hour = DatePart(DateInterval.Hour, Now())
Minute = DatePart(DateInterval.Minute, Now())
Second = DatePart(DateInterval.Second, Now())
strDate = Month & “/” & Day & “/” & Year & “ “ & Hour & “:” & Minute & “:” & Second
Date_to_SQL_DateTime = Date.ParseExact(strDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture)
strDate returns
1/24/2017 23:17
Error I'm receiving is
String was not recognized as a valid Datetime

Try below. Need to make sure parameters are of same format as specified in the ParseExact function.
Dim Month As String = Nothing
Dim Year As String = Nothing
Dim Day As String = Nothing
Dim Hour As String = Nothing
Dim Minute As String = Nothing
Dim Second As String = Nothing
Dim strDate As String = Nothing
Dim Date_to_SQL_DateTime As Date
Month = DatePart(DateInterval.Month, Now()).ToString("00")
Year = DatePart(DateInterval.Year, Now()).ToString("0000")
Day = DatePart(DateInterval.Day, Now()).ToString("00")
Hour = DatePart(DateInterval.Hour, Now()).ToString("00")
Minute = DatePart(DateInterval.Minute, Now()).ToString("00")
Second = DatePart(DateInterval.Second, Now()).ToString("00")
strDate = Month & "/" & Day & "/" & Year & " " & Hour & ":" & Minute & ":" & Second
Date_to_SQL_DateTime = DateTime.ParseExact(strDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture)

Related

VBA, Dynamically pickup a date

I have a file I want to pickup from the previous wednesday June 10th. I will be running my code today (Sunday June 14th). However this will reoccur every week.
Is there a way I can make my code dynamic enough to pickup the previous wednesday date?
Here is my code Set wbTarget = Workbooks.Open("C:\extract\Business_Report_20200527.xlsx")
Can I alter that path to dynamically pickup a date?
Thank you.
Try this:
Dim today As Date
Dim IntervalType As String
Dim FilePath As String
today = Date()
IntervalType = "d"
While Weekday(today) <> vbWednesday
today = DateAdd(IntervalType, -1, today)
Wend
FilePath = "C:\extract\Business_Report_" + Format(today, "yyyymmdd") + ".xlsx"
Set wbTarget = Workbooks.Open(FilePath)
Another way to do it:
Sub Test()
MsgBox "Last Wednesday: " & PreviousWednesday & vbCr & _
"Wednesday prior to 9th June: " & PreviousWednesday(DateValue("9 June 2020")) & vbCr & _
"Last Wednesday formatted: " & Format(PreviousWednesday, "yyyymmdd")
'Your code:
'Set wbTarget = Workbooks.Open("C:\extract\Business_Report_" & Format(PreviousWednesday, "yyyymmdd") & ".xlsx")
End Sub
Public Function PreviousWednesday(Optional CurrentDate As Date) As Date
If CurrentDate = 0 Then CurrentDate = Date
PreviousWednesday = (CurrentDate - Weekday(CurrentDate, vbMonday) + 1) - 5
End Function

i want to create a VBA code in Word that will create multiple word files with different file names

I want to create multiple saves of the same word file using visual basic. each file will need to be named with the day of the month and month name (not numbers) i want this to run from the 1 to 31 on each month. i have a rough code,
Sub Mine()
Dim DateStr, FileStr As String
DateStr = Format$(Date, "DD")
FileStr = DateStr & ".docx"
ActiveDocument.Save
ChangeFileOpenDirectory "Z:\FIR MASTER FOLDER\FCR briefing sheet\2018\Test"
ActiveDocument.SaveAs2 FileName:=FileStr, FileFormat:=wdFormatXMLDocument
End Sub
now how do i add the loop and the day and month format part
try the below. If you want in the format you mention in comment simply put as
Debug.Print monthName & " " & i
Saving to different folders in an amendment to your original question. I am happy to update but this should deal with your initial question as posed.
It works with the current month. You would want a test to make sure doesn't already exist. I tried to show you each of the functions you might consider and how you could structure a loop.
Uses a function from here for end of month.
Sub test()
Dim myDate As Date
Dim myMonth As Long
myDate = Date
Dim monthName As String
monthName = Format$(myDate, "mmmm")
Dim endOfMonth As Long
endOfMonth = CLng(Format$(dhLastDayInMonth(myDate), "dd"))
Dim i As Long
For i = 1 To endOfMonth
Debug.Print monthName & " " & i
Next i
End Sub
Function dhLastDayInMonth(Optional dtmDate As Date = 0) As Date
' Return the last day in the specified month.
If dtmDate = 0 Then
' Did the caller pass in a date? If not, use
' the current date.
dtmDate = Date
End If
dhLastDayInMonth = DateSerial(Year(dtmDate), _
Month(dtmDate) + 1, 0)
End Function
So save with the filename you would do something like:
For i = 1 To endOfMonth
ActiveDocument.SaveAs fileName:= "C:\Test\" & monthName & " " & i, FileFormat:=wdFormatXMLDocument
Next i
Reference:
http://www.java2s.com/Code/VBA-Excel-Access-Word/Word/TosaveadocumentwithanewnameusetheSaveAsmethod.htm
Or to create folders for the year:
Sub AddFoldersAndFiles()
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
'Dim fso As FileSystemObject ' ''early binding. Requires reference to MS Scripting runtime
'Set fso = New FileSystemObject ''early binding
Dim myYear As Long
Dim endOfMonth As Long
Dim filePathStub As String
filePathStub = "C:\Users\User\Desktop\" ' path to create folders at
myYear = Year(Date)
Dim monthsArray() As Variant
monthsArray = Array("January","February","March","April","May","June","July","August","September","October","November","December")
Dim currentMonth As Long
For currentMonth = LBound(monthsArray) To UBound(monthsArray)
Dim folderName As String
folderName = filePathStub & monthsArray(currentMonth) & CStr(myYear)
folderName = fso.CreateFolder(FolderName)
endOfMonth = CLng(Format$(dhLastDayInMonth(DateSerial(myYear,currentMonth + 1, 0)),"dd"))
Dim currentDay As Long
For currentDay = 1 To endOfMonth
ActiveDocument.SaveAs2 FileName:= folderName & Application.PathSeparator & monthsArray(currentMonth) & " " & currentDay, FileFormat:= wdFormatXMLDocument
Next currentDay
Next currentMonth
End Sub

Dlookup returns null when data exists

Hi I have been trying this for hours and it doesn't matter how much I search to try different options I cannot get the lookup for give a result that I am looking for. I am testing it using a date and work code that I know is in the table that I am referring to.
I am using the input box to provide the date and fixing the work code as 13 (Dispatch). The lookup should be returning the date in the table as the date input is in the table. My code is:
Sub Append_Dispatch()
Dim dbs As Object
Dim qdf As querydef
Dim InputDateString As String
Dim InputDate As Date
Dim RtnDate As String
Dim chkDate As Date
Dim WC As Long
Set dbs = CurrentDb
Set qdf = dbs.querydefs("Dispatch Append to Production Data")
WC = 13
InputDateString = InputBox("Please enter start date to import", "Date")
InputDate = DateValue(InputDateString)
RtnDate = DLookup("[Date of Action]", "Production Data", "[Date of Action]= #" & InputDate & "# AND [Work Code] = " & WC & "")
chkDate = DateValue(RtnDate)
If InputDate = chkDate Then
IB = MsgBox("This dispatch date has already been entered:" & vbCrLf & "Please check and use a date after " & Dte, vbOKOnly, "Date Error")
Exit Sub
End If
'qdf.Parameters("Dispatch Date").Value = InputDate
'qdf.Execute
'qdf.Close
'Set qdf = Nothing
'Set dbs = Nothing
End Sub
Also I cannot get the code to work after the end if to input the parameter and run the append query. But that is another issue.
Any ideas please.....

Issue with Counter and a Date

I am havving a little issue with a date like the 1AM bellow but if I use a date like this it works fine "MAR 28, 2014 3PM" for some reason I get a "-17:49" while using the 1AM.. why is this?
Dim myTime As String = "MAR 26, 2014 1AM"
Dim date1 As DateTime = System.DateTime.Now.ToString("hh:mm:ss dddd, dd MMMM yyyy")
Dim date2 As DateTime = Convert.ToDateTime(myTime)
Dim ts As New TimeSpan
ts = date2 - date1
If ts.Days > 0 Then
TextBox.Text = ts.Days & ":" & ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds
ElseIf ts.Hours > 0 Then
TextBox.Text = ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds
Else
TextBox.Text = ts.Minutes & ":" & ts.Seconds
If ts.Minutes = 2 And ts.Seconds < 30 Then
doStop = True 'we are 2:30 minutes away from closing
End If
If ts.Minutes < 15 Then
'TextBox.text = "Ending Soon"
End If
End If
You are converting the current date/time to string, then auto-converting it back to a date value immediately on that second line.
Dim date1 As DateTime = System.DateTime.Now.ToString("hh:mm:ss dddd, dd MMMM yyyy")
^^^^^^^^ this converts date to string
^^^^^^^^ this converts it back due to implicit casting
But since you are using hh as the format, you get only the 12-hour value of the date, so some information about the date value is lost.
For example, it is currently 12:34 AM EST where I am testing the code, but if I dump out the contents of date1 immediately after that second line, it has already become 12 hours later!
3/26/2014 12:34:41 PM
When you want to work with date values and do math on them, leave them as date values. Don't convert to string until you're ready to display something to the user. So just use:
Dim date1 as DateTime = System.DateTime.Now

Setup a count down based on a time

I would like to know how to setup a count down based on a time.. for example its 6pm and there is a time like 11PM, how would I have a countdown that I click a button no timer, that shows me you have 5 hours left etc.
Dim myTime As String = "7AM"
Dim date1 As DateTime = Date.Now
Dim date2 As DateTime = Convert.ToDateTime(Date.Now.Date.ToLongDateString & " " & myTime)
Dim ts As New TimeSpan
ts = date2 - date1
TextBox.Text = ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds
If I got it right, do you want to get the remaining time by clicking a button? which also means that you have to click it everytime for it to update?
Dim myTime As String = "7AM"
Dim date1 As DateTime = System.DateTime.Now.ToString("hh:mm:ss tt, dd MMMM yyyy")
Dim date2 As DateTime = Convert.ToDateTime(Date.Now.Date.ToLongDateString & " " & myTime)
Dim ts As New TimeSpan
If date2 < date1 Then
date2 = date2.AddDays(1)
End If
ts = date2 - date1
MsgBox(ts.Hours & ":" & ts.Minutes & ":" & ts.Seconds)
That would return a time with 16:30:00 with hh:mm:ss format.