You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA夏令时判断函数始终返回False的技术求助

Troubleshooting Your VBA Daylight Saving Time Function

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 Explicit at 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 Date value 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:29:03