调用Day1WeekNum & Day1inMonth 的主要函数
Function NthDay(Date1)
' Tells you if a date is the 3rd Tuesday of the Month
Dim Day1Name, Day1WeekNum, A, B, DayName, Nth
Dim Status ' Tells you if there is anything in the rest of the Array
Dim cWeekNum ' Number for the current week
Dim WeekDiff 'Difference between the week numbers
Dim cDayNum 'Number for the day of the week for Date1
Dim Week1Num
Week1Num = Day1WeekNum(Date1) ' tells me the week number of the first day of the month
Day1Name = Day1inMonth(Date1) ' tell me the day of the week for the first day of the month
第1天代码
Function Day1inMonth(Date1)
'Tells you the weekday of the first day in a month of the provided date
Dim cYear, cMonth, month1st, day1
cYear = Year(Date1)
cMonth = Month(Date1)
month1st = DateSerial(cYear, cMonth, 1)
day1 = Weekday(month1st, vbSunday)
Day1inMonth = day1
End Function
第 1 天周数
的代码Function Day1WeekNum(Date1 As Date)
'Tells you the week of the first day of the month of the provided date
Dim cYear, cMonth, day1Week
Dim month1st As Date
cYear = Year(Date1)
cMonth = Month(Date1)
month1st = DateSerial(cYear, cMonth, 1)
day1Week = WorksheetFunction.WeekNum(month1st, 1)
Day1WeekNum = day1Week
End Function
我不得不将上面的代码更改为下面的代码,以阻止不匹配错误。我不知道为什么。它是否必须与可变范围或其他内容相关?我试图理解,以便将来可以避免错误的原因。
允许它工作的新代码:
Function Day2WeekNum(Date1)
'Tells you the week of the first day of the month of the provided date
Dim cYear1, cMonth1, day1Week1
Dim month1st1 As Date
cYear1 = Year(Date1)
cMonth1 = Month(Date1)
month1st1 = DateSerial(cYear, cMonth, 1)
day1Week1 = WorksheetFunction.WeekNum(month1st, 1)
Day2WeekNum = day1Week1
End Function
作用域中有一个局部变量和一个函数,它们具有相同的名称 -Day1WeekNum
局部变量隐式是一个变量,因为它尚未声明为任何特定类型。变体可以包含数组以及单个(标量(值。
赋值Week1Num = Day1WeekNum(Date1)
看起来像函数调用,但实际上是在尝试访问数组。尚未定义任何数组,因此会出现类型不匹配错误。如果为Week1Num
变量提供显式非数组/非变量类型,则错误将更改为"编译错误:预期的数组"。
更改函数名称有效,因为新函数名称与调用过程中的任何局部变量都不匹配。若要避免将来出现此问题,请执行以下操作:
- 使用每个模块顶部的
Option Explicit
(通过打开 VBA中的工具和选项>>编辑器中的"需要变量声明" 编者( - 给每个变量一个显式类型 - 例如
Dim Day1WeekNum As Integer
- 避免声明与范围内的 sub 或函数同名的变量,因为这可能会造成混淆并导致问题