VBA excel calendar/date 选择器有日期问题

VBA excel calendar/date picker has date issue

这来自一个视频教程,但是当我转到 运行 时,该月的第一天没有出现在该月的正确星期几中。

我相信(尽管我无法确认)问题与在 ShowDate() 中找到的 'Year' 的使用有关:

last_date = VBA.DateSerial(**Year**(first_date), Month(first_date) + 1, 1) - 1

我不禁想到,如果 Year 是 last_date 中的问题,那么 Month 也会证明是类似的问题,但理想情况下解决方案也是相同的。

我看过类似的教程,它们都遵循相同的结构,但我 运行 遇到了同样的问题。不确定它是我的 computer/excel 程序的设置还是完全是其他东西?错误代码为

编译错误:参数数量错误或 属性 赋值无效

完整代码如下。

    Private Sub cmbMonth_Change()

If Me.cmbMonth.Value <> "" And Me.cmbYear.Value <> "" Then
    Call ShowDate

End If
End Sub
Private Sub UserForm_Initialize()

Dim i As Integer

With Me.cmbMonth
    For i = 1 To 12
        .AddItem VBA.Format(VBA.DateSerial(2019, i, 1), "MMMM")
    Next i
    
    .Value = VBA.Format(VBA.Date, "MMMM")
    
End With

With Me.cmbYear
    For i = VBA.Year(Date) - 3 To VBA.Year(Date) + 4
        .AddItem i
    Next i
    
    .Value = VBA.Format(VBA.Date, "YYYY")
    
End With

End Sub
Sub ShowDate()

Dim first_date As Date
Dim last_date As Date

first_date = VBA.CDate("1-" & Me.cmbMonth.Value & "_" & Me.cmbYear.Value)
last_date = VBA.DateSerial(Year(first_date), Month(first_date) + 1, 1) - 1

Dim i As Integer
Dim btn As MSForms.CommandButton

''''to remove any caption from buttons
For i = 1 To 34
    Set btn = Me.Controls("CommandButton" & i)
    btn.Caption = ""
Next i

''''set first date of the month
For i = 1 To 7
    Set btn = Me.Controls("CommandButton" & i)
        If VBA.Weekday(first_date) = i Then
        btn.Caption = "1"
    End If
Next i


Dim btn1 As MSForms.CommandButton
Dim btn2 As MSForms.CommandButton

''''set all dates
For i = 1 To 33
    Set btn1 = Me.Controls("CommandButton" & i)
    Set btn2 = Me.Controls("CommandButton" & i + 1)
    
    If btn1.Caption <> "" Then
        If VBA.CInt(btn1.Caption) < VBA.Day(last_date) Then
            btn2.Caption = btn1.Caption + 1
        End If
  
Next i

End Sub

所以事实证明,名称为 Year 的对象、变量或函数是在代码中定义的(而不是在显示的部分中)。此 Year 隐藏了常规 VBA 函数 Year 并导致编译器消息。

如果想强制VBA使用build-in函数,可以通过全局VBA-object访问,只需要写VBA.Year.

但是,最好避免使用此类名称来避免歧义。