【发布时间】:2022-06-13 18:33:44
【问题描述】:
这来自一个视频教程。当我运行这个时,该月的第一天没有出现在该月的正确星期几中。
我认为问题是 ShowDate() 中这一行的 年份:
last_date = VBA.DateSerial(Year(first_date), Month(first_date) + 1, 1) - 1
类似的教程遵循相同的结构,但我遇到了同样的问题。
错误是
编译错误:参数数量错误或属性分配无效
完整代码。
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
【问题讨论】:
-
你应该对
first_date也使用DateSerial(使用Val函数将字符串转换为数字),但是如果你坚持使用CDate,你应该替换@中的下划线字符987654326@ 带连字符。 -
未提交给 Cdate。如果我正确理解了您的建议,我进行了以下更改 first_date = Val(VBA.DateSerial("1-" & Me.cmbMonth.Value & "-" & Me.cmbYear.Value)) last_date = Val(VBA.DateSerial(Year (first_date), Month(first_date) + 1, 1) - 1) 仍然出现同样的错误
-
DateSerial(Val(Me.cmbYear.Value), Val(Me.cmbMonth.Value), 1) -
遗憾的是没有变化。您是否偶然看到代码中的任何其他错误。我相信我准确地转录了它。我认为问题可能出在表单本身,但在那里找不到任何错误?
-
哪一行会报错?我只是看到您的代码在
Next i之前缺少End If,但我看不出是什么导致“参数数量错误”错误。
标签: excel vba excel-2010