Excel VBA: date format in user form - excel

I have various text boxes in a user form with dates pulled from my worksheets, but all the dates are in US format (m/d/yyyy).
I'm using the ControlSource property to copy the date, e.g.:
ControlSource='SKU Data'!N2
Is there a way to reformat the dates so they appear as d/m/yyyy?
The dates in the worksheets are already formatted to d/m/yyyy.

Do it with Strings:
Sub dural()
txt = "12/25/2014"
a = Split(txt, "/")
txt = a(1) & "/" & a(0) & "/" & a(2)
MsgBox txt
End Sub

Related

date subtraction doesn't appear correctly vhen generating .log file

I currently have a log file that get generated when you click on a button.
At the beginning of the .log you have a preview with different information such as the login, url of a server etc... But you also have the date of the beginning of the process and the date for the end. Both are in the long date format and are displayed correctly in the log file.
That log file takes the information from a sheet the preview part is static and is a range ("A1:C13") and the rest of the log is beneath but still in the columns ("A:C").
The cells in excel :
I want to add a line that shows the difference between the two date, to quickly see the time the process took.
However when I'm creating the log file, I get the time difference in number.
eg : in excel the cell with the format shows 00:01:55 but in the log file I get 0,001331
The output in the .log :
So far I tried :
To force the format in vba when the export in processing
To copy/paste in value with the hour format to not show the subtraction in the cell
different kind of format but it wasn't conclusive
You'll find the code that create the log file here :
Private Sub iExportLog(Optional LogPath As String, Optional bouton As String)
Dim NF As Integer, C As Range, posi As Integer
Dim date_nom As String
Dim drct As String
NF = FreeFile
drct = ThisWorkbook.path & "\_LogELB"
Set C = iFLog.Range("A1")
' iFLog = the sheet
' Things I tried :
'iFLog.Range("C12") = Format(iFLog.Range("C11").Value - iFLog.Range("C2").Value, "hh:mm:ss")
'iFLog.Range("C12").NumberFormat = "hh:mm:ss"
'
posi = InStrRev(ThisWorkbook.Name, ".")
If Dir(drct, vbDirectory) = "" Then MkDir (ThisWorkbook.path & "\" & "_LogElb")
date_nom = Format(CStr(Now), "yyyy_mm_dd_hh_mm_ss_")
If LogPath = "" Then LogPath = drct & "\" & bouton & "_" & date_nom & ".log"
Open LogPath For Append As #NF
Do While C.Value <> ""
Print #NF, C.Value & vbTab & vbTab & vbTab & C.Offset(0, 1).Value & vbTab & C.Offset(0, 2).Value
Set C = C.Offset(1, 0)
Loop
Close #NF
End Sub
I don't have a lot of practice with manipulating dates but I know that it can be painful.
Is there a way to display a date subtraction correctly when generating a .log/.txt file ?
If you write a formatted time string to a cell then Excel will interpret that as a time value and "undo" your formatting, converting the value back to a numeric value (though the display format may hide that).
If you want to keep the "hh:mm:ss" format then first set the cell format to "Text", or prepend the string with ' before placing it in the cell. Or read the cell's Text property instead of Value

Convert date to Date Function

I want to convert a date in a cell to the date function so it is a formula. How do I get the date (using VBA), any date, say, 13 Jun 2020 to =DATE(2020, 6, 13) using variables for the year, month, and day. My code I have tried but won't work. The activecell shows 13-Jun-2020 as a date but appears in the function box as 13/06/2020
Sub ConvertDateToDateFunction()
Dim mvDay, mvMth, mvYr As Integer
mvDay = Left(ActiveCell, 2)
mvMth = Mid(ActiveCell, 4, 2)
mvYr = Right(ActiveCell, 4)
ActiveCell.Value = "=DATE(mvYr, mvMth, mvDay)"
End Sub
You have two problems. Here is the solution to the smaller one. The code below would do what you intend. It would convert a text string in the ActiveCell to a function of similar value and insert it in the cell below the ActiveCell.
Sub ConvertDateToDateFunction()
' if you don't say what it's supposed to be it'll be a Variant
Dim mvDay As String, mvMth As String, mvYr As String
mvDay = Left(ActiveCell.Value, 2)
mvMth = Mid(ActiveCell.Value, 4, 2)
mvYr = Right(ActiveCell.Value, 4)
ActiveCell.Offset(1).Formula = "=DATE(" & mvYr & "," & mvMth & "," & mvDay & ")"
End Sub
It's not entirely easy to insert a date as a text string in Excel because Excel will try to recognize a date for a date. Observe that any part of a string is a string, not an integer.
Now about your much bigger problem which is that you don't understand how Excel handles dates. It is such a big problem because you are trying to create a date in Excel in various ways and you run into all sorts of trouble. Read up on the subject here.
To give you a taste of what you will learn: what you see displayed in a cell isn't what the cell contains. There might be a formula in it and you see a number. And there might be a date and you see a string. What you see is determined by the cell's format. I think Chip Pearson's article will cover that topic. If you need to know more, look for "Cell formatting" on the web.
Your macro won't work because the date is a "real date" and not a string.
Try the following to convert the contents of cells containing a real date to a formula which will return the same date:
Option Explicit
Sub dtToFormula()
Dim R As Range, C As Range
Dim vDateParts(2)
Set R = [a1:a10]
'Set R = ActiveCell 'or Selection whatever range you want to convert
For Each C In R
If IsDate(C) And Not C.HasFormula Then
vDateParts(0) = Year(C.Value2)
vDateParts(1) = Month(C.Value2)
vDateParts(2) = Day(C.Value2)
C.Formula = "=DATE(" & Join(vDateParts, ",") & ")"
End If
Next C
End Sub

Find Next File in Folder based on Name

I have a folder with files, all named by date. I have the file name (date) that I'm looking for, in cell E2. The cell has already been formatted so that it's in the same format as the file names. Here's what I have so far:
Sub Step2Importsheet()
Sheets.Add Type:= _
"E:\MyFolder\Manipulated Data\Test\" & Range("E2").Text & ".csv"
End Sub
This code works great if the date in cell E2 exists as a file in the folder.
Now here's my problem: In some cases, I have a date listed in E2 that does not exist as a file in the folder. I want to expand the code so that if it doesn't exist, it looks for the next sequential date until it finds a file. (In most cases this will be one or two dates after the date in E2 but it might go as far as five days out. It will never hit an indefinite loop).
Appreciate any and all help!
Something like this should work for you:
Sub LookForFile()
Dim sBaseFolder As String
Dim objFSO As Object
Dim datFileName As Date
Set objFSO = CreateObject("FileSystemObject")
sBaseFolder = "E:\MyFolder\Manipulated Data\Test\"
' Initalize date
datFileName = CDate(Range("E2"))
Do While Not objFSO.FileExists(sBaseFolder & GetFileNameFromDate(datFileName) & ".csv")
datFileName = DateAdd("d", 1, datFileName)
' Maybe place a limit here in case file doesn't exist
Loop
' datFileName should now contain the date of a matching file
End Sub
Function GetFileNameFromDate(ByVal p_date As Date)
' Returns YY-MM-DD format
GetFileNameFromDate = Year(p_date) & "-" & Right("0" & Month(p_date), 2) & "-" & Right("0" & Day(p_date), 2)
End Function
The GetFileNameFromDate function lets you specify the file name format since I imagine it's not a direct date but probably a string with the slashes removed.
Thanks everyone! The code below works well. I had to use Range instead of Date because I had to convert it to Text for it to be able to work as a file name.
Dim newdate As Range
Set newdate = Range("E2")
Do Until Dir("E:\MyFolder\Manipulated Data\Test\" & newdate.Text & ".csv") <> vbNullString
newdate = newdate + 1
Loop
Sheets.Add Type:="E:\MyFolder\Manipulated Data\Test\" & newdate.Text & ".csv"

How to extract big text from Excel cell in a formatted text with Excel formulas?

I have below text in Excel cell:
$abcd.$efghijk.$lmn.$op.$qrst.
I want above text in following format in Excel cell using Excel formula only:
abcd$abcd.efghijk$efghijk.lmn$lmn.op$op.qrst$qrst.
Here's what I will suggest based on discussion.
In a general module, insert following code.
Public Function RepeatCustom(strInput As String) As String
Dim varInput As Variant
Dim i As Long
If Len(strInput) = 0 Then
RepeatCustom = ""
Else
varInput = Split(strInput, ".")
For i = LBound(varInput) To UBound(varInput)
RepeatCustom = RepeatCustom & " " & Mid(varInput(i), 2, Len(varInput(i))) & varInput(i)
Next
RepeatCustom = Replace(Trim(RepeatCustom), " ", ".") & "."
End If
End Function
And then assuming cell containing original data is A2, you can use above UDF:
=RepeatCustom(A2)
Just note that the code is minimum and is based on sample posted.

Convert date to a number

I have written a macro which reads the cell content and opens corresponding files as per the cell value.
For example, if I provide 20140522 in a cell, it opens the file "C:\Files\20140522.csv".
However, instead of providing in the above format if I provide it as 22/05/2014 or more generally today's date, how can I convert it into above format in the vba script itself ?. This is because all my files are in the format shown in example only. Following is my macro code
Sub Open()
num=Cells(1,1).Value
ActiveWorkbook.Open(FileName:="C:\Files\" & num & ".csv")
End Sub
You can use Format:
num = Format(Cells(1,1).Value, "yyyymmdd")
Consider:
Sub dural()
Dim d As Date, sDate As String
d = Date
sDate = CStr(Year(d) & Format(Month(d), "00") & Format(Day(d), "00"))
ActiveWorkbook.Open Filename:="C:\Files\" & sDate & ".csv"
End Sub

Resources