0

So I am trying to format a date to yyyymm (e.g. 201808). However, it always comes out as (20188). On months with double digits such as december, there isnt a problem. It would come out as 201812. However this doesnt happen for months with single digits. In my code, the month and year were originally in two separate columns, but I combined them. Here is my code:

Sheets("Sheet1").Select
Columns("G:G").Select
Selection.NumberFormat = "00"
Columns("I:I").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("I2").Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(RC[-1],RC[-2])"
Selection.AutoFill Destination:=Range("I2:I800")
Range("I2:I800").Select
Columns("I:I").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Application.CutCopyMode = False
Columns("G:H").Select
Selection.Delete Shift:=xlToLeft

There are probably easier ways to write this code, as I just recorded the macro.

5
  • 1
    Use the TEXT function to "reapply" the format when concatenating. Commented Aug 13, 2018 at 17:05
  • @rawrplus Hmm, unfortunately I cannot put it in that format because it cannot be interpreted that way to another system. It must be "yyyymm". Could i possibly do "yyyy.mm" and delete the period afterwards? Commented Aug 13, 2018 at 17:06
  • @BigBen, true but that isn't remotely what the op is doing here. The string concatenation doesn't use the cell's number format. Commented Aug 13, 2018 at 17:07
  • If you are exporting to TXT or CSV, doesn't a cell date format of yyyymm produce the correct results? Commented Aug 13, 2018 at 17:08
  • @Jeeped - my point exactly. OP is expecting that it does... Commented Aug 13, 2018 at 17:10

1 Answer 1

1

Number format <> actual number.

You need to use TEXT() to actually change the stored value:

With Worksheets("Sheet1").Range("I2:I800")
    .FormulaR1C1 = "=RC[-1] & TEXT(RC[-2],""00"")"
    .Value = .Value
End With
Worksheets("Sheet1").Columns("G:H").Delete
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.