dd / mm / yyyy和hh:mm:ss到yyyymmddhhmmss

时间:2016-10-10 05:41:12

标签: excel vba excel-vba macros excel-2007

excel image

A栏是日期,B栏是我想要的日期格式。

为了转换它,我附上了vba代码:

Sub dateformat()

Dim ws As Worksheet    
    For Each ws In ActiveWorkbook.Worksheets
        ws.Columns("B:B").NumberFormat = "yyyymmdd;@"
    Next ws
End Sub

结果1: 这段代码给了我B列

当我更改B列的格式以使其与时间合并时:

它显示为C列(日期格式):

Sub a()
Worksheets("Sheet1").Activate    
Worksheets("Sheet1").Columns(2).Select 'or 

Worksheets("SheetName").Range("b:b").Select    
Selection.NumberFormat = "@"    
End Sub

我想将日期与时间= dd/mm/yy(第1列),hh:mm:ss(第2列)合并到yyyymmddhhmmss(第3列)。

1 个答案:

答案 0 :(得分:0)

因此,在我认为这应该有效之后澄清你的内容,因为数据实际上是日期和时间格式。

Sub combine()
Dim str1, str2 As String

'Making sure you're only applying it to the cells that have date/time next to them
lastrow1 = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row

'Defining your ranges
Set rng1 = ActiveSheet.Range("A1:A" & lastrow1)
Set rng2 = ActiveSheet.Range("B1:B" & lastrow1)
Set rng3 = ActiveSheet.Range("C1:C" & lastrow1)

rng1.NumberFormat = "yyyymmdd"
rng2.NumberFormat = "hhmmss"
rng3.NumberFormat = "@"

For i = 1 To lastrow1
str1 = Range("A" & i).Text
str2 = Range("B" & i).Text

Range("C" & i) = str1 & str2
Next i

End Sub