我有12张纸,连续12个月,每个月都有随机的日期,可以手动在A栏中输入。让我们以一月为例:
当我在单元格A1中输入数字 25 时,我希望该单元格自动返回 25/01/2019 在A1(!)中(或根据需要,在01/25/2019中)。即使使用自定义设置,Excel自动填充功能也无法做到这一点,所以我想:VBA吗?
我认为代码应该看起来像这样(带有更改事件):
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
那是我的位置。我很确定,这对于使用月份并输入许多日期的人来说可能是有用的代码。我离真相远吗?它甚至可行吗?我了解这可能听起来有些复杂。
答案 0 :(得分:1)
尝试
If Target.value2 > 0 and Target.value2 <= 31 Then
Target.Value2 = dateSerial(year(now), month(now), Target.Value2)
End If
答案 1 :(得分: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