仅输入日期(jj)填写日期(jj / mm / yyyy)

问题描述 投票:0回答:2

我有12张纸12个月,每月随机日期手动输入A栏。让我们以1月份为例:

当我在单元格A1中输入数字25时,我希望单元格在A1(!)(或01/25/2019,如您所愿)中自动返回25/01/2019。即使使用自定义设置,Excel自动填充功能也无法做到这一点,所以我想:VBA?

我认为代码看起来应该是这样的(带有change事件):

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, cell As Range
    Set rng = Range("A:A")
    If Not Application.Intersect(rng, Range(Target.Address)) _
           Is Nothing Then

           '???
           'If cell entered in range is a number Then
           'change value to "number" & "/01/2019" 

    End If
End Sub

这就是我所处的位置。我很确定这对于那些使用月份和进入许多日期的人来说可能是一段有用的代码。我离真相很远吗?它甚至可以吗?我知道它可能比听起来更复杂。

excel vba autofill real-time-updates
2个回答
0
投票
Option Explicit    

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim AffectedRange As Range
    Set AffectedRange = Application.Intersect(Me.Range("A:A"), Target)

    If Not AffectedRange Is Nothing Then
        Dim Cell As Range
        For Each Cell In AffectedRange.Cells
            If Cell.Value >= 1 And Cell.Value <= 31 Then
                Application.EnableEvents = False
                Cell.Value = DateSerial(2019, 1, Cell.Value)
                Cell.NumberFormat = "YYYY-MM-DD"
                Application.EnableEvents = True
            End If
        Next Cell
    End If
End Sub

1
投票

尝试

If Target.value2 > 0 and Target.value2 <= 31 Then
   Target.Value2 = dateSerial(year(now), month(now), Target.Value2)
End If
© www.soinside.com 2019 - 2024. All rights reserved.