简体   繁体   中英

VBA Format Function not working

Last week I created this macro that allows me to create a record of my data. It places the data next to the date and is set to replace the date if we are still on the same date (and if not move on to the current date). This is the code:

Sub Record()

'Get all the dates
'Selecting the data to copy
Range("C23:O23").Select
Selection.Copy

'Find the last used row in Column B
Dim LastRow As Range
With ActiveSheet
    Set LastRow = .Cells(.Rows.Count, "B").End(xlUp)
End With

'if still today, replace data, if not record the data on the next line
If LastRow = Format(Date, "dd/mm/yyyy") Then
    LastRow.Offset(0, 1).Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, 
Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Else
    LastRow.Offset(1, 0).Value = Format(Date, "dd/mm/yyyy")
    LastRow.Offset(1, 1).Select
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, 
Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

End If

Application.CutCopyMode = False

End Sub

The thing is, that last week it worked perfectly. Today when I turned it on, it seems to put the date in American format (07/02/2018 as opposed of 02/07/2018) even though I set the format in the vba code. Thisa renders the macro useless as it still checks against English date format and so skips a line every time I click the button.

Any help would be very much appreciated.

Looking through your code I'm wondering if part of the problem is that you're adding dates to the last cell using FORMAT which returns a string.
In place of LastRow.Offset(1, 0).Value = Format(Date, "dd/mm/yyyy") just use LastRow.Offset(1,0) = Date .

To correct the dates already on the sheet you could multiply the values by 1, or add 0 to convert them to numbers rather than text (and then format as dates):

  • Enter 1 into any empty cell and copy the cell.
  • Highlight your dates, right-click and select Paste Special .
  • In the Paste Special dialog box select Multiply and hit OK.

This code should also work if the Paste Special method doesn't, but I don't feel it's solving the root of the problem.

If CDATE(LastRow) = Date Then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM