Excel VBA夏令时判断函数始终返回False的技术求助
Hey there! Let's fix that misbehaving function step by step—there are a couple of key issues causing it to always return False:
1. Critical Variable Name Typo (The Immediate Culprit)
Look closely at your calling code:
isvaldst = isdaydat(Me.dtefrm.Value) If isvaldat = True Then ' <-- Here's the problem! Me.dayconf.Value = "Daylight" Else Me.dayconf.Value = "Regular" End If
You assigned the function's result to isvaldst, but then checked against isvaldat (a completely different, undeclared variable). Since isvaldat defaults to Empty, the condition isvaldat = True never evaluates to true—hence you always see "Regular".
Fix: Correct the variable name in your If statement:
isvaldst = isdaydat(Me.dtefrm.Value) If isvaldst = True Then Me.dayconf.Value = "Daylight" Else Me.dayconf.Value = "Regular" End If
2. Ambiguous Date Parsing (Potential Hidden Issue)
Your function uses CDate("3/9/2008"), which relies on your system's regional date settings. If your system uses dd/mm/yyyy format (common in Europe, Australia, etc.), this will be parsed as September 3, 2008 instead of March 9, 2008—completely shifting your date range.
Fix: Use DateSerial(year, month, day) to create dates unambiguously, regardless of regional settings:
Public Function isdaydat(ByVal datval As Date) As Boolean Select Case True Case datval > DateSerial(2008, 3, 9) And datval < DateSerial(2008, 11, 1) isdaydat = True Case Else isdaydat = False End Select End Function
3. Bonus Optimizations
To make your code cleaner and more robust:
- Add
Option Explicitat the top of your module—this forces you to declare all variables, catching typos like the one above immediately. - Simplify the function by returning the boolean expression directly (no need for
Select Case):Public Function isdaydat(ByVal datval As Date) As Boolean isdaydat = (datval > DateSerial(2008, 3, 9) And datval < DateSerial(2008, 11, 1)) End Function - Pass the raw
Datevalue instead of the formatted text from your textbox to avoid unnecessary type conversion:fixdat = CDate(Me.dtefrm.Value) Me.dtefrm.Value = Application.WorksheetFunction.Text(fixdat, "mm/dd/yyyy") ' Fixed "yyy" to "yyyy" for full year isvaldst = isdaydat(fixdat) ' Use the already-converted Date variable
内容的提问来源于stack exchange,提问作者brokenspiv

