PDA

View Full Version : Solved: Excel forces text into date format



antlee
06-19-2013, 06:17 AM
I have a line of code

rngCell.value = iVar1 & " - " & iVar2

but the trouble is that when iVar1 and iVar2 are low numbers Excel turns this automatically to a date.

So instead of getting

12 - 24 in my cell I get 24/12/2013.

Any ideas? I could format the cell before assigning a value to it but is there a direct way.

Thanks
Ant

SamT
06-19-2013, 06:42 AM
rngCell.text = iVar1 & " - " & iVar2

antlee
06-19-2013, 06:50 AM
Thanks for replying but when I try

Sub test()
Range("A1").Value = 12 & "-" & 24
Range("A2").Text = 12 & "-" & 24
End Sub

I get an error on the second line

Run-time error '424':
Object required

I've done some looking and apparently .Text is read only

Thanks
Ant

antlee
06-19-2013, 07:40 AM
I worked out how to do it

Range("A1").Value = "'" & 12 & "-" & 24

SamT
06-19-2013, 08:46 AM
Sub test()
Dim iVar1 As Integer
Dim iVar2 As Integer
iVar1 = 12
iVar2 = 24
Range("A1").NumberFormat = "@"
Range("A1").Value = iVar2 & "-" & iVar1
Range("A2") = "'" & iVar1 & "-" & iVar2 'First term is apostrophe in double quotes
End Sub
Interestingly, once the value has been formatted as Text by either of those methods, it remains Text even when pasted, (or by using =A1,) into cells formatted as Date or Number. It does, however, loose the leading Apostrophe.

Edit: Posted without reading your post.
ReEdit: You have to set the NumberFormat first, else Excel converts the value to a date, the formats the date as Text.