通过仅输入日期在 Excel VBA 中创建确切的日期
Creating exact dates in Excel VBA by inputing only the day
在下图的 Excel sheet 中,第一列的标题以及之后每 7 列的标题都包含月份和年份。
我正在想一些代码,可以更快地在这些标题下输入完整的日期。由于月份和年份已经存在,我认为必须有一种方法可以只输入一天并获得全部内容。例如,如果在单元格 A26 中输入“21”,则结果为“2/21/2015”。
有人知道我如何得到这个输出吗?
编辑:多亏了这个论坛上的有用回复,我才弄清楚如何做到这一点。这是我的成品代码,以防有人想做类似的事情:
Private Sub Worksheet_change(ByVal Selection As Range)
Set Sel = Selection
If Sel.Count > 1 Then
Exit Sub
End If
If (Sel.Column - 1) Mod 7 = 0 Or Sel.Column = 1 Then
'在我的例子中,日期列总是遵循 1、8、15 的模式...
If Sel.Value > 31 Or Sel.Value = "" Then
Exit Sub
Else
Sel.NumberFormat = "General"
Sel.Value = Left(Cells(1, Sel.Column), InStr(Cells(1, Sel.Column), ",") - 1) & " " & _
Sel.Value & Right(Cells(1, Sel.Column), 6)
Selection.NumberFormat = "m/d/yyyy"
End If
End If
End Sub
如何输入天数,选择输入这些天数的范围,运行如下:
Sub Add_month_year()
Dim c As Range
For Each c In Selection
c = Left(Cells(1, c.Column), InStr(Cells(1, c.Column), ",") - 1) & " " & _
c.Value & Right(Cells(1, c.Column), 6)
Next
End Sub
这应该 return 日期代码中的完整日期,然后您可以根据需要设置格式。
在下图的 Excel sheet 中,第一列的标题以及之后每 7 列的标题都包含月份和年份。
我正在想一些代码,可以更快地在这些标题下输入完整的日期。由于月份和年份已经存在,我认为必须有一种方法可以只输入一天并获得全部内容。例如,如果在单元格 A26 中输入“21”,则结果为“2/21/2015”。
有人知道我如何得到这个输出吗?
编辑:多亏了这个论坛上的有用回复,我才弄清楚如何做到这一点。这是我的成品代码,以防有人想做类似的事情:
Private Sub Worksheet_change(ByVal Selection As Range)
Set Sel = Selection
If Sel.Count > 1 Then
Exit Sub
End If
If (Sel.Column - 1) Mod 7 = 0 Or Sel.Column = 1 Then
'在我的例子中,日期列总是遵循 1、8、15 的模式...
If Sel.Value > 31 Or Sel.Value = "" Then
Exit Sub
Else
Sel.NumberFormat = "General"
Sel.Value = Left(Cells(1, Sel.Column), InStr(Cells(1, Sel.Column), ",") - 1) & " " & _
Sel.Value & Right(Cells(1, Sel.Column), 6)
Selection.NumberFormat = "m/d/yyyy"
End If
End If
End Sub
如何输入天数,选择输入这些天数的范围,运行如下:
Sub Add_month_year()
Dim c As Range
For Each c In Selection
c = Left(Cells(1, c.Column), InStr(Cells(1, c.Column), ",") - 1) & " " & _
c.Value & Right(Cells(1, c.Column), 6)
Next
End Sub
这应该 return 日期代码中的完整日期,然后您可以根据需要设置格式。