I'm having a problem getting a date formatted correctly when copying to a worksheet on a blank/un-formatted line.
I am using a macro to copy values from one sheet to another and I want one column to contain the current date that the script was run on.
Here is what I have:
records_list.Worksheets("Sheet1").Range("J" & records_row_number) =
Format(Date, "ddmmmyy")
This is working correctly in that it is putting a date value in to the target sheet (records_list). However, the formatting is coming in as "d-mmm-yy" which means it contains the dashes and drops the leading zero in the days.
I want the date in the format 09Oct18 but it is displaying as 9-Oct-18
I cannot for the life of me figure out why it's doing this or how to prevent it. I've tried lots of suggestions for date formatting I've seen on other sites but nothing is working. If I go into the cell formatting and force it to "ddmmmyy" it displays correctly, however, I want to avoid pre-formatting thousands of rows in the sheet so that it opens/saves faster.
Excel uses the range's numberformat when choosing how to display a date, not the format it was written to the range in. To change the numberformat of the range, you can do something like:
With records_list.Worksheets("Sheet1").Range("J" & records_row_number)
.Value = Date
.NumberFormat = "ddmmmyy"
End With
This needs to be done in two step. First enter Value and then set Number Format:
records_list.Worksheets("Sheet1").Range("J" & records_row_number).Value = Date
records_list.Worksheets("Sheet1").Range("J" & records_row_number).NumberFormat = "ddmmmyy"
or even better using With:
With records_list.Worksheets("Sheet1").Range("J" & records_row_number)
.Value = Date
.NumberFormat = "ddmmmyy"
End With
Related
Still a novice at VBA but learning and ran up what i believe is a pretty advanced request.
I have a workbook our managers use that has 5 worksheets created each month. Each one is suffixed by the current Month_YYYY. I am trying to add an Xlookup to the worksheet whose date is one month prior (same prefix) and fill down to the last row.
So in this example, in B2 of the Oasis_Detail_November_2022 worksheet I would have:
=IFERROR(XLOOKUP(A2,'Oasis_Detail_October_2022'!A:A,'Oasis_Detail_October_2022'!B:B),C2) In December, it would reference the November tab and so on.
Is it even possible to do this? If it helps, the order of the tabs are always the same and i'm always looking 5 back (this example I hid a column just for screenshot room).
This is my rudimentary code thusfar. Thanks for the help.
Sub Oasis_Detail_Formatting()
Rows(2).EntireRow.Delete
Columns("A").Cut
Columns("C").Insert
[A:A].Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
Columns("B").Insert
Range("B1").Value = ("Svc Rel Parent")
ActiveSheet.UsedRange.EntireColumn.AutoFit
End Sub
I tried to use a Dim Dt As String and Dt = Format(Date, "mmmm_yyyy") statement within the Xlookup code but everyway i formatted the function, i just kept getting a debug error.
Simple task with confusing alternate results.
I'm copying a range of data using:
WS.Range("A2:Z" & lRow).Copy
ThisWorkbook.Worksheets("Import").Range("A2:Z" & lRow).PasteSpecial xlPasteValues
The first column from the copy sheet is a date in format 12/05/2017 01:00:00 (note the double space in between date and time)
In one instance of this the date values are pasted across fine and come out as dates - great!
In another instance of this the date values are pasted but come out as 14/05/2017 01:00 and these aren't registering as dates, rather as a text string.
I noticed I could go through the dates cell by cell and press enter which converted them to dates, so I tried using .range("A1:A100").value = .range("A1:A100").value to no avail.
I suspect it may have something to do with the day-month-year format as opposed to being month-day-year (since it works for a sheet that starts on 12-may but not on 14-may) but (1) could there be another difference, (2) why does pressing ENTER work fine and (3) how can I emulate pressing ENTER on my whole range of cells (bearing in mind .value = .value doesn't work)
In short: Type conversion (fixing the values before they cause trouble on your worksheet in the first place) is absolutely the best way to go.
In long:
Let's start with these two values:
22.05.2017 12:00
22.05.2017 12:00
I'll place the first in A1 and the second in B1. Note that Excel will often try to do the type conversion, so in this case I'll manually enforce A1 to contain text values by formatting the cell as such after-the-fact.
Let's verify:
Using the Immediate window, we can see that the compiler recognizes the content of A1 as a pure text value, while it recognizes the content in B1 as a date value.
The solution you need is to ensure that any text values are converted to date values:
Option Base 1
Sub pasteTextAsDate()
Dim dateArr As Variant
Dim rng As Range
Set rng = ThisWorkbook.Worksheets(1).Range("A1:A3")
' In the line below, we fill the variant variable with the content of the range, casting the variable into an array of variants
dateArr = rng
' For the sake of proving this code works, we'll start by printing the content and what type it is
For Each s In dateArr
Debug.Print s & " - " & TypeName(s)
Next s
For i = 1 To UBound(dateArr)
' This is where we loop through the array and cast any string values to date values
dateArr(i, 1) = CDate(dateArr(i, 1))
' Here we verify for ourselves that the conversions are OK
Debug.Print dateArr(i, 1) & " - " & TypeName(dateArr(i, 1))
Next i
' And here we print the result to the worksheet
ThisWorkbook.Worksheets(1).Range("C1:C3").Value = dateArr
End Sub
Result:
I am working on a model that requires me to sort data in a range by date, before copying the data into a different template on another sheet. Every row has a formula that pulls data from Bloomberg, so even if the cell looks empty, excel recognizes that there is content in the cell. Sorting the date column as it is does not work, as excel wont recognize the data that Bloomberg pulls as a date, so it would be sorted from A to Z, which scrambles the dates instead.
To work around this, I inserted and adjacent column with the formula (using cell A1 as an example) "=(A1+0)" that then allows the column to be sorted from new to old. The problem here is that if cell A1 does not display a date (in other words, it appears empty yet the cell contains a formula that leaves the cell looking empty if no date is pulled) it returns a #VALUE! error and sorting new to old would put the errors at the top (Thank you Excel for this fantastic feature, btw).
To work around this new issue, I replaced the above formula in the cell with "=IFERROR(A1+0,1)" which gives me the date 1/1/1900. Fine, now the data is sorted in the manner I want it, but I have a bunch of ancient dates that just make my end product look ugly.
I have two questions, first; how can I use VBA to delete the data in the cells where the date equals 1 (which shows the date 1/1/1900), and only those cells? Or, alternatively, only copying the rows above the cell that contains 1/1/1900. This is a relatively small amount of cells that would be affected by this, 40 at most.
Second; is there a different way of sorting the data using VBA that I am missing, that might be more efficient?
Try this macro, I tried to test it with as many anomalies as possible.
Sub SortByDateColumnH()
Dim r As Range: Set r = Sheet1.Range("B3:P40")
Dim cel As Range
For Each cel In r.Columns(7).Cells
If IsError(cel.Value) Then
cel.Value = 0
ElseIf Not IsDate(cel.Value) Then
cel.Value = 0
Else
cel.Value = CLng(cel.Value)
End If
Next
r.Columns(7).NumberFormat = "0"
r.Sort Key1:=r.Cells(1, 7), Order1:=xlDescending, Header:=xlNo
For Each cel In r.Columns(7).Cells
If cel.Value < 100 Then cel.ClearContents
Next
r.Columns(7).NumberFormat = "m/d/yyyy" '<-- set the format to your preference
'r.Copy Destination:=someDestination ' you can copy the range by code if needed
End Sub
Hoping there is a way this can be done with a formula since I will be putting this on SharePoint as a shared workbook.
Column B contains Tasks, while Column E contains the Date and Time of when the Task was assigned. Is there a formula that would automatically enter the current date and time in Column E whenever someone entered data into column B?
Any assistance would be greatly appreciated.
Another way to do this is described below.
First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation. Then set maximum iterations to 1000.
The 1000 iterations doesn't matter for this formula, but it stops excel getting stuck in an infinite loop for other circular references.
After doing this, use the following formula.
=If(D55="","",IF(C55="",NOW(),C55))
Once anything is typed into cell D55 (for this example) then C55 populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.
This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.
This can be accomplished with a simple VBA function. Excel has support for a Worksheet Change Sub which can be programmed to put a date in a related column every time it fires.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
End If
End Sub
A quick explanation. The following "if" statement checks for two things: (1) if it is the second column that changed (Column B), and (2) if the cell 3 columns over (Column E) is currently empty.
If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
If both conditions are true, then it puts the date into the cell in Column E with the NOW() function.
Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
Range.Offset
Range.Column
Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.
open Excel
press "Alt+F11"
Double-click on the worksheet that you want to apply the change to (listed on the left)
copy/paste the code below
adjust the Range(:) input to correspond to the column you will update
adjust the Offset(0,_) input to correspond to the column where you would like the date displayed (in the version below I am making updates to column D and I want the date displayed in column F, hence the input entry of "2" for 2 columns over from column D)
hit save
repeat steps above if there are other worksheets in your workbook that need the same code
you may have to change the number format of the column displaying the date to "General" and increase the column's width if it is displaying "####" after you make an updated entry
Copy/Paste Code below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date
End Sub
Good luck...
I'm afraid there is not such a function. You'll need a macro to acomplish this task.
You could do something like this in column E(remember to set custom format "dd/mm/yyyy hh:mm"):
=If(B1="";"";Now())
But it will change value everytime file opens.
You'll need save the value via macro.
You can use If function
Write in the cell where you want to input the date the following formula:
=IF(MODIFIED-CELLNUMBER<>"",IF(CELLNUMBER-WHERE-TO-INPUT-DATE="",NOW(),CELLNUMBER-WHERE-TO-INPUT-DATE),"")
Here is the solution that worked for me
=IF(H14<>"",NOW(),"")
I created a conditional formatting to change the color based on value compare for one cell, but I don't know how to apply this formatting for the whole column and even other columns? (do I have to use for loop to set the formatting for all the cells?)
'add conditionalFormating for one cell.
Set rngCell = Cells(6, 7)
Set objCF = rngCell.FormatConditions.Add _
(Type:=xlExpression, _
Formula1:="=" & rngCell.Address & " > " & rngCell.offset(, -3).Address)
'set formats for new CF
With objCF
.Font.ColorIndex = 26
.Interior.ColorIndex = 19
End With
Thanks in advance
Unfortunately, Excel 2007/2010 don't have as extensive a macro record function as earlier versions
If you are referencing other cells when applying conditional formatting, a good method is to apply it to one cell (which you know how to do), and then copy the formatting to the rest of the column; if you are filling down a column, this should not cause you to lose other cell formats you may wish to keep
So I would start your code with
rngCell.FormatConditions.Delete
Then once the format is added, you can simply use:
rngCell.Copy
rngOut.PasteSpecial xlPasteFormats
, where rngOut is defined as starting with rngCell and filling down to the last row in the table
To apply to other columns, you would probably need a different formula as there are different offsets. To minimise the required code, you could always manually add the full set of formats/conditional formats you want to a hidden row just above the table's headers. Then you can copy all of these to your table using code of the form...
Range("A1:J1").Copy
Range("A3:J100").PasteSpecial xlPasteFormats
...if we assume your header gets pushed down to row 2 when you add the formatted row in row 1
Although I have referred to cell addresses in the above example, I would always recommend referring to range names and using cells notation e.g. Range("A1") is Cells(1, 1). The use of range names to define columns in tables is covered in more detail in this expert Excel video. The benefits are immense...if your header row is defined with a range name, you can insert a new row above your table without having to re-write any code