使用宏复制时如何修改日期?

时间:2019-07-04 19:26:41

标签: excel vba excel-2010 number-formatting

我正在VBA中编写宏。我有一个循环,遍历日期列表,分钟为00,15.30.45的每个条目都将日期和时间复制到新列中。这只是我正在处理的代码的一部分,因此这就是现在看来毫无意义的原因。我的麻烦是我需要修改复制到新列中的时间。我需要日期保持不变,但必须修改时间,以便:

hh:00 becomes   hh-1:45
hh:15 becomes   hh  :00
hh:30 becomes   hh  :15
hh:45 becomes   hh  :30

我现在拥有的代码下面,并且一切正常,但是显然它不会修改时间,因为我只是弄明白我想做什么。修改小时和分钟需要什么代码?谢谢!

Dim X As Integer

Range("A2").Select
NumRows = Range(Selection, Selection.End(xlDown)).Rows.Count
Range("A2").Select

For X = 2 To NumRows
    If (Minute(ActiveCell.Value) = 0) Then
        Range("D2").Value = ActiveCell.Value
        Range("D2").NumberFormat = "YYYY-MM-DD HH-1:45"
    ElseIf (Minute(ActiveCell.Value) = 15) Then
        Range("D2").Value = ActiveCell.Value
        Range("D2").NumberFormat = "YYYY-MM-DD HH:00"        
    ElseIf (Minute(ActiveCell.Value) = 30) Then
        Range("D2").Value = ActiveCell.Value
        Range("D2").NumberFormat = "YYYY-MM-DD HH:15" 
    ElseIf (Minute(ActiveCell.Value) = 45) Then
        Range("D2").Value = ActiveCell.Value
        Range("D2").NumberFormat = "YYYY-MM-DD HH:30"
    End If

    Selection.Offset(1, 0).Select
Next X

1 个答案:

答案 0 :(得分:0)

我正在一家烧烤店(Happy 4th of JULY EVERYONE)上,这似乎比这里的客人要有趣。

因此,要像您对inutes那样增加时间,您可能应该使用TimeSerial Function。我试图修改您的代码以执行您所说的操作,但说实话,这在bar-b-Q期间很难。

一些建议。

  1. Don't use select
  2. Don't use Integer
  3. 向日期添加4小时3分8秒。...TimeSerial(4, 3, 8)

这是我尝试更改代码以获取所需内容的方法。您应该能够推断我的意思。

Sub Running_From_That_Water_Like_My_Name_Was_TedKennedy()

Dim X As Long, WSheet As Worksheet, increaseAMOUNT As Double


Set WSheet = ActiveSheet '<---- make sure this is correct

With WSheet


Dim aCell As Range: Set aCell = .Range("A2")
Dim increaseAMOUNT As Double: increaseAMOUNT = TimeSerial(0, 15, 0) 'this adds `15 minutes



For X = 2 To Range(Range("A2"), Range("A2").End(xlDown)).Rows.Count


    If (Minute(ActiveCell.Value) = 0) Then

    Range("D2").Value = aCell.Value + increaseAMOUNT '<----you can modify the amount to increase consistently or include your own TimeSerial
    Range("D2").NumberFormat = "YYYY-MM-DD HH-1:45"


    ElseIf (Minute(aCell.Value) = 15) Then
    Range("D2").Value = aCell.Value + increaseAMOUNT
    Range("D2").NumberFormat = "YYYY-MM-DD HH:00"

    ElseIf (Minute(aCell.Value) = 30) Then
   Range("D2").Value = aCell.Value + increaseAMOUNT
    Range("D2").NumberFormat = "YYYY-MM-DD HH:15"

    ElseIf (Minute(aCell.Value) = 45) Then
    Range("D2").Value = aCell.Value + increaseAMOUNT
    Range("D2").NumberFormat = "YYYY-MM-DD HH:30"


    End If



    Set aCell = aCell.Offset(1, 0)

    Next X
End With


End Sub
'People-I-know.Girls.Count = 0