Home » excel » excel – Application.UserName modifies the number format

excel – Application.UserName modifies the number format

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a cell in an Excel file that I want to populate with the current date&time and the user name. The cell is populated by clicking a button.

Until now I was not using the function Application.UserName and the date & time output was formatted correctly (e.g: 07.01.2014 16:57)

After I have added the & Space(1) & Application.UserName piece of coding the formatting of date & time is not formatted the way I want (depending on the user that populates the cell I get results like: 09-Jan-14 11:30:13 + USERNAME or 1/7/2014 5:59:43 PM + USERNAME)

I guess that it takes the formatting from the user’s regional settings, correct ?

My question is how can I override those settings as it looks that the ActiveCell.NumberFormat = "dd.mm.yyyy hh:mm" piece of code is no longer working good.

Below is my code:

Private Sub CommandButton1_Click()
    ActiveCell = Now() & Space(1) & Application.UserName
    ActiveCell.NumberFormat = "dd.mm.yyyy hh:mm"
End Sub
How to&Answers:

The Date/Time NumberFormat will only work if the cell has a valid Date/Time. So the trick is to change the format first and then add the username.

Is this what you are trying?

With ActiveCell
    .Value = Now()
    .NumberFormat = "dd.mm.yyyy hh:mm"
    .Value = .Text & Space(1) & Application.UserName
End With