I have a cell with a time value as 1:23:45 AM and would like to display just the hour value or use it for other calculations. Need to do this using vba. No, I cannot format the column manually.
Thanks,
Sam
To use VBA to format the cell to only display the hour:
With Worksheets("Sheet1").Cells(1, 1)
.NumberFormat = "H"
End With
To read the hour value in VBA (regardless of how the cell is formatted):
Dim hourValue As Integer
With Worksheets("Sheet1").Cells(1, 1)
If (IsDate(Format(.Value, "hh:mm:ss"))) Then
hourValue = Hour(.Value)
Else
// handle the error
End If
End With
If you want to use the displayed value in code without performing the conversion in VBA then use the Text property of the cell (Range) rather than the Value property. You'll need to be sure that the cell is formatted correctly first:
Dim hourValue As Integer
With Worksheets("Sheet1").Cells(1, 1)
If ((.NumberFormat = "H") And _
(IsDate(Format(.Value, "hh:mm:ss")))) Then
hourValue = CInt(.Text)
Else
// handle the error
End If
End With
If you just want to use the hour value in a worksheet formula then use the HOUR() worksheet function - e.g. =HOUR(A1)
Finally, if you cannot format the column manually because the sheet is protected then you won't be able to format it in VBA either
I am not sure whether your cell is a time field or not. If it is, can you do the following?
dim h as integer
h = Hour(Cell(1,1))
Related
I have a vba formula that copies a value (which consists in a number) of a cell to another cell. When the number is with decimals (ex: 25,50), the result is ok, but when the number is without decimals (ex: 50), I get an error checking flag suggesting me to convert that cell to number.
I wouldn't have a problem with this error flagging, but I cannot use the result in a formula. For example, if I use SUM(A:A), the formula adds all the numbers, except the flagged ones.
So far, I have tried pasting using the .xlPasteValuesAndNumberFormats property, without any success.
Sub Adauga()
Dim i As Range
Dim cellTaxa As Range
Set cellTaxa = ActiveSheet.Buttons(Application.Caller).TopLeftCell.Offset(1, -2) 'Here I set the range to the value of a cell that is related to the button I click.
n = 2
Set i = Sheets("TJT DETERMINABILA").Cells(n, 10) 'Here I insert the first result
Do While i <> "" 'Here I find the next empty cell in the same column to insert the value.
n = n + 1
Set i = Sheets("TJT DETERMINABILA").Cells(n, 10)
Loop
cellTaxa.Copy 'Here I copy the cell
i.PasteSpecial xlPasteValues 'Here I paste the cell.
End Sub
I would like to be able to use the values that are pasted in the column I mentioned in the code with the SUM formula.
Thank you!
As #urdearboy has stated, an easy trick to convert text to numbers is to add +0.
In my case, I have added cellTaxa = CellTaxa + 0 before the line cellTaxa.Copy and it has solved my issue.
I need to keep the cells formatted as text and at the same time make sure that Excel calculates the formulas within them.
Is there a way to do it?
Embed your excel-formulas in the text-function.
=Text(your function,"#")
more info:
https://support.office.com/en-us/article/text-function-20d5ac4d-7b94-49fd-bb38-93d29371225c
edit: If your formulas are not being evaluated, then there can also be other causes for that than the cell-formatting.
I'm solved it!!!
In a Sheet module:
Option Explicit
Private Busy As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Busy Then
Busy = True
If ActiveSheet.ProtectContents Then ActiveSheet.Protect UserInterfaceOnly:=True
CalculateFormula Target.Row, Target.Column
Busy = False
End If
End Sub
In a standard module:
Option Explicit
Sub CalculateFormula(Row As Long, Column As Long)
Dim Format As String
If Left(Cells(Row, Column).Value, 1) = "=" Then
Format = Cells(Row, Column).NumberFormat
Cells(Row, Column).NumberFormat = "General"
On Error Resume Next
Cells(Row, Column).FormulaLocal = Cells(Row, Column).Value
On Error GoTo 0
Cells(Row, Column).NumberFormat = Format
End If
End Sub
It is unclear if you just need the format of the cell to be text, or if your need the results of a formula in a cell to be converted to a string/text. Excel formulas do no affect cell formatting, nor or are they affected by cell formatting. a perfect example of this is dates. Dates are really an integer counting the number of days since a start point. Day 1 is 1900/01/01 on a pc (On a mac I think its 1905/01/01 but could be wrong). If you enter today's date (2018/09/17) in any default cell, Excel identifies it as a date, changes the formatting of the cell and converts the date to 43360. You will see this if you change the cell format back to general and you will note that the number is right aligned. If you change the format of the cell to text, you will still see 43360 but instead it will be left aligned. More importantly its still a number and you can test it by using ISTEXT(A1) where A1 is the cell in question. It will still return true.
In order to make the contents of a cell a string, you can simply concatenate your formula with "".
=Your_Function&""
=1+1&""
Having said that. If a cell is formatted as a string, the FORMAT of the cell will remain a string despite whatever math calculation goes on inside it. So if you format A2 as text, and then place =1+1 inside it, the result in the cell will be the number 2 and the cell will be formatted as text.
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 have some dates in a string in a column.
Because the format seems to be M/DD/YYYY I sometimes get a VALUE error when using DATEVALUE.
How can I convert a column to make sure all dates are correct.
For example, the following 2 cells
9/29/2006 12:49:58.956 AM DATEVALUE gives an error
9/12/2008 5:36:59.356 PM DATEVALUE converts to 39791
You need to select the range (just one colunm) with the dates... Go to:
(in Excel 2010)
Data >>> Text to Columns
Inside the dialog box select:
Delimited >>> Next
Just select Tab checkbox.
And heres is the magic!
You need to define the arrangement for your dates...
In the Date field:
Choose the what you need (as you say in your question is M/D/Y)
Destination field:
Make sure that is the same of the data you want to format.
And finish.
The problem you are having is probably that the data is getting interpreted as a general field, and shows up as, say 49:59.0 - which isn't text, which is what Datevalue() expects as input; for both inputs, Datevalue(CellID) words if you prepend the text with a ' - which ensures it is treated as text.
it seems that your system settings use dd/mm/yyyy for short date format. and datevalue function uses this settings, so its try to read the day from the first part of the string and the month from the second part. as in your example 9/29/2006 12:49:58.956 AM there is no month with 29 then it gives error, and in the second example it gives 39791 = 9 december 2008 and NOT 12 september 2008.
If you change the short date format in your system settings to mm/dd/yyyythen datevalue function will work correctly, but this not acceptable, so we need to replace month with day and day with month to get correct date.
I don't know if we can do this with Excel formula but we can do that simply with VBA.
So try this code:
Sub Test()
Dim d1 As Variant, d2 As Variant, td As Date
Dim Rng As Range, CL As Range
Set Rng = Range("A1:A2") ' change this to your range
For Each CL In Rng
d1 = Split(CL.Value, " ")
d2 = Split(d1(0), "/")
td = DateSerial(d2(2), d2(0), d2(1))
CL.Offset(0, 1) = td
CL.Offset(0, 1).NumberFormat = "mm/dd/yyyy" ' change the Date format as you need
'CL.Offset(0, 1).NumberFormat = "dd/mm/yyyy"
Next
End Sub
I have a sheet whit mixed format data (dates, double, strings, etc.).
I search the value (my_index) in the lookup_range and I want to retrieve the data to change with it a cell in other sheet. It works fine, but when the value returned by VLookup is a date and I set it to the other sheet it looses its date format.
Dim lookup_range As Range
Dim my_index, my_value As Variant
my_value = Application.VLookup(my_index, lookup_range, num_col, False)
Sheets(3).Cells(num_row, last_col_s1 + num_col - 1).Value = my_value
So, when the data in the lookup_range is 02/05/2014 the data showed at sheet-3 looks like 41761.
I need to keep the original data format of the data in the lookup_range.
VLOOKUP doesn't care about the formatting of the data it's returning - it returns data, not formats.
The only way to ensure the same format as the source, is to copy/paste that format, either manually or programmatically.
use this
Sheets(3).Cells(num_row, last_col_s1 + num_col - 1).Value = cdate(my_value)
I had the same problem, and simply reformatted the VLOOKUP cell to also be in date-time format. That fixed my issue. I am not sure how date-time gets translated into a number, but it does.
i faced the same issue. After vlookup, change the format to "ShortDate" format. This will give you what you are looking for.
Excel Formula :
=TEXT(VLOOKUP(Lookup_value,table_array,col_index_num,0),"dd-mm-yyyy")
VBA :
Sub vlookup_code()
Dim table_rng As Range
'FOR THE TIME BEING GIVING A LOOKUP VALUE
look_up_value = "sekar"
'SETTING THE TABLE ARRAY RANGE
Set table_rng = Sheet1.Range("C3").CurrentRegion
'SINCE VLOOKUP WILL GIVE AN ERROR, IF THE LOOKUP VALUE IS NOT PRESENT
'TO HANDLE THIS ERROR, WE USE THE ISERROR STATEMENT
If IsError(Application.vlookup(look_up_value, table_rng, 2, 0)) = False Then
vlook_value = WorksheetFunction.vlookup(look_up_value, table_rng, 2, False)
'CHANGING THE VLOOKUP VALUE FORMAT TO DATE FORMAT
date_format = WorksheetFunction.Text(vlook_value, "dd-mm-yyyy")
End If
End Sub
In Microsoft Office 2016.
Once data copied to the cell. Select the column which needs to be in date format. Right click->format cells, go to Number tab and select date from the drop-down and choose the required date format, data will be converted to date format.