A2=201604
I am trying to pick up value from a Cell(Date) and use the same for saving the file.
But while saving instead of the date a value is being printed, see code below:
Dim part1 as string
part1 = Range("A2").Value
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\xxx- " & Format(part1, "MMM-YYYY") & ".xlsx" , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
201604 is not a date. It is just a number.
You could use something like
myDate = "01/" & right(a2,2) & "/" left(a2,4)
string yourAnswer = format(myDate, "MMM-YYYY")
The problem is you're prematurely casting the Date into a String by using the part1 variable, so the 'date' is already broken and not recognisable as a date by the time it hits your Format() call.
Either declare part1 as a Date or just skip the whole part1 declaration and insert Range('A2').Value directly into the Format() call.
Related
This the following code that I have:
Public Function Import_Multi_Excel_Files()
Dim InputFile As String
Dim InputPath As String
InputPath = "L:\Directory\To\Project\Data\"
InputFile = Dir(InputPath & "*.xls*")
worksheetName = "WorksheetThatHasData!A:H"
Do While InputFile <> ""
DoCmd.TransferSpreadsheet acImport, , "Table_1", InputPath & InputFile, -1, worksheetName, True '< The true is for column headers
InputFile = Dir
Loop
End Function
The above code is grabbing all of the data from a specific worksheet within each workbook (which is good) and importing it into MS Access. But I noticed that our reports always include the current month and previous month even though the report is dated for the current month. Every file name has the format Report - YYYYMM. The idea I'm kicking around is something that will look at the YYYYMM portion of the file name and only grab the data with that corresponding date.
Edits and Additions Below
Actuarial_Report-201705
Enrollment_Report-201705
Premium-Data-201705
Each of the above reports includes information from May AND April. But the previous months report will clearly include data from April but also March, and so on. What's happening is that all the data I've imported counted enrollment, premium, and actuarial info twice. I want to only pull 201705 data from the 201705 reports and have the code ignore the 201704 info.
Replace your While loop with the following:
Dim strMonth As String
Dim strYear As String
Do While InputFile <> ""
strMonth = Mid(InputFile, Len(InputFile) - 6, 2)
strYear = Mid(InputFile, Len(InputFile) - 10, 4)
DoCmd.TransferSpreadsheet acImport, , "Table_1", InputPath & InputFile, -1, worksheetName, True '< The true is for column headers
CurrentDb.Execute "DELETE * From Table_1 WHERE MyDateColumn < #" & strYear & "/" & strMonth & "/01#"
InputFile = Dir
Loop
Where MyDateColumn is the column where you store dates.
Assumptions: You are not storing any other old information in Table_1 that you want to keep, else you would want to import to another table, remove the invalid date info, and then append the data to Table_1
The end of the file name cannot change, else this will generate bugs.
Note that I'm not using parameters in my query, but since the string is from a filename and has a max length of 6 with a / in the middle, the risk of SQL injection is not present.
I have the following function in my worksheet...
Format(Range("AG1"), "mm")
I'm using it to auto-populate the saveas filename, which is a larger function, but it all works except for this part. As part of that larger function there is
Year(Range("AG1"))
which is returning the correct year in "yyyy" format. (It doesn't require any specific formatting, it just returns the year in 4-digit format.)
However, the first function, Format(Range("AG1"), "mm") is always returning 01, indicating that is is January, which it isn't always. I need the month based on the current date to be returned in "mm" format.
The Range("AG1") refers to a cell in the worksheet that has a date entered as [mm/dd/yyyy].
Any ideas what I'm doing wrong?
According to this table you should be using "m"
No. Formatting code Display as Example
1 ddd Weekday name Sat
2 dddd Weekday name Saturday
3 mmm Month name Jan
4 mmmm Month name January
5 m Month 1
6 d Day 17
Here's the final code that worked for me...
Private Sub btnCreate_Click()
ActiveSheet.Copy
Application.ExecuteExcel4Macro "show.toolbar(""Ribbon"",False)"
ActiveSheet.Shapes.Range(Array("btnCreate")).Select
Selection.Delete
ActiveWorkbook.SaveAs "C:\Users\" & (Environ$("Username")) & "\Desktop\" & "Timecard, " & Year(Range("AG1")) & "-" & Format(Range("AG1"), "mm") & " - " & _
Range("R2").Value & ", " & Range("T2").Value, xlOpenXMLWorkbookMacroEnabled
ActiveWindow.Close
End Sub
I am a fairly new to vba coding and would appreciate some help as I play around with some code. I am trying to edit a URL to make searching for historical exchange rates dynamic
original code:
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://www.x-rates.com/historical/?from=USD&amount=1&date=2017-04-20", _
Destination:=Range("A1"))
.PostText = "currency_exchange_practice"
My new code that doesn't work:
Dim dateday, datemonth, dateyear As Long, fulldate As Variant
Columns("A:D").ClearContents
dateday = Day(Range("G2"))
datemonth = Month(Range("G2"))
dateyear = Year(Range("G2"))
fulldate = dateyear & "-" & datemonth & "-" & dateday
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://www.x-rates.com/historical/?from=USD&amount=1&date=" & fulldate & "", _
Destination:=Range("A1"))
.PostText = "currency_exchange_practice"
It is also erasing all my data in cells g2, including a button I have made that are not in cells A:D. Please and thank you for your help!!
I think the issue is with your use of Month
Month for April will return 4 not 04 so when you pass in fulldate to the URL you are passing in 2017-4-20 instead of 2017-04-20. If I pass in fulldate as you have it, I get nothing returned.
To remedy this issue I would first declare your date parts as strings so we can use the Format function. An important note here is that you must declare each variable with a datatype. As you have it written, dateday and datemonth are Variants because they are not explicitly given a data type.
Dim dateday As String, datemonth As String, dateyear As String, fulldate As String
Then you can do this:
dateday = Format(Day(Range("G2")), "00")
datemonth = Format(Month(Range("G2")), "00")
Now, fulldate will look like 2017-04-20 and should work.
I did confirm that the website you are using expects a two digit value for the day as well.
I am not sure why it would be erasing anything in column G except if your query table somehow overlaps it when it is placed in A1.
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.
In the code below, I'm using the current date and time, with the help of which I am generating a file name. My problem is that it's giving me an output without leading zeros:
Dim strDateTime As String = DateTime.Now.Day.ToString() & "" & _
DateTime.Now.Month.ToString() & "" & DateTime.Now.Year.ToString() & "" & _
DateTime.Now.Hour.ToString() & "" & DateTime.Now.Minute.ToString() & "" & _
DateTime.Now.Second.ToString() & DateTime.Now.Millisecond.ToString()
For example, my query is giving output as below currently:
Assume time is 1:5:30 :: hh:mm:ss
Required output is: 01:05:30
How can I achieve this?
Try this,
DateTime.Now.Hour.ToString("00") & ":" & DateTime.Now.Minute.ToString("00") & ":" & DateTime.Now.Second.ToString("00")
EDIT :
As suggested by 'mdb' in the answers, using Custom Date and Time Format Strings would be more efficient and cleaner
DateTime.Now.ToString("hh:mm:ss tt") '12 Hour format with AM/PM designator, Eg :- 09:01:01 PM
DateTime.Now.ToString("HH:mm:ss") '24 Hour format Eg :- 21:01:01
Instead of concatenating strings, which is highly inefficient, you'll want to use String.Format. This also supports Custom Date and Time Format Strings, which make it trivial to achieve what you want.