Excel VBA 用户表单 - 如何 increase/decrease 约会一个月
Excel VBA Userform - How to increase/decrease date by one month
使用以下代码,我使用 SpinButtons 增加了 TextBox 中显示的日期值。
MainUserForm_Initialize()
DateTextBox.Value = Format(Date, "dd-mm-YYYY")
...
End Sub
'Add one day when spinning up.
Private Sub SpinButtonDate1_SpinUp()
With DateTextBox
.Value = Format(DateAdd("d", 1, .Value), "dd-mm-yyyy")
End With
End Sub
'Remove one day when spinning down.
Private Sub SpinButtonDate1_SpinDown()
With DateTextBox
.Value = Format(DateAdd("d", -1, .Value), "dd-mm-yyyy")
End With
End Sub
问题是,如果我向下旋转到 11-07-2015,它会从 12-07-2015 变为 06-12-2015 而不是 11-07-2015。这是为什么? (我在增加值时遇到同样的问题。给出的日期只是一个例子。)
如果我将区域格式设置为美国,我只会遇到同样的问题。尝试此修复程序,无论您的区域设置如何,它都应该有效:
'Add one day when spinning up.
Private Sub SpinButtonDate1_SpinUp()
With DateTextBox
.Value = Format(GetDateFromUK(.Value) + 1, "dd-mm-yyyy")
End With
End Sub
'Remove one day when spinning down.
Private Sub SpinButtonDate1_SpinDown()
With DateTextBox
.Value = Format(GetDateFromUK(.Value) - 1, "dd-mm-yyyy")
End With
End Sub
Function GetDateFromUK(sDate As String, Optional sSeparator As String = "-") As Date
Dim vParts
vParts = Split(sDate, sSeparator)
GetDateFromUK = DateSerial(vParts(2), vParts(1), vParts(0))
End Function
使用以下代码,我使用 SpinButtons 增加了 TextBox 中显示的日期值。
MainUserForm_Initialize()
DateTextBox.Value = Format(Date, "dd-mm-YYYY")
...
End Sub
'Add one day when spinning up.
Private Sub SpinButtonDate1_SpinUp()
With DateTextBox
.Value = Format(DateAdd("d", 1, .Value), "dd-mm-yyyy")
End With
End Sub
'Remove one day when spinning down.
Private Sub SpinButtonDate1_SpinDown()
With DateTextBox
.Value = Format(DateAdd("d", -1, .Value), "dd-mm-yyyy")
End With
End Sub
问题是,如果我向下旋转到 11-07-2015,它会从 12-07-2015 变为 06-12-2015 而不是 11-07-2015。这是为什么? (我在增加值时遇到同样的问题。给出的日期只是一个例子。)
如果我将区域格式设置为美国,我只会遇到同样的问题。尝试此修复程序,无论您的区域设置如何,它都应该有效:
'Add one day when spinning up.
Private Sub SpinButtonDate1_SpinUp()
With DateTextBox
.Value = Format(GetDateFromUK(.Value) + 1, "dd-mm-yyyy")
End With
End Sub
'Remove one day when spinning down.
Private Sub SpinButtonDate1_SpinDown()
With DateTextBox
.Value = Format(GetDateFromUK(.Value) - 1, "dd-mm-yyyy")
End With
End Sub
Function GetDateFromUK(sDate As String, Optional sSeparator As String = "-") As Date
Dim vParts
vParts = Split(sDate, sSeparator)
GetDateFromUK = DateSerial(vParts(2), vParts(1), vParts(0))
End Function