Excel-VBA当月的第一个工作日

时间:2018-06-28 10:30:33

标签: excel vba

我有一个workbook_open宏,如下所示;

select * from dual@A_B_DBLINK;

G1中的公式如下;

Private Sub Workbook_Open() Sheets("Staff List").Activate If Range("G1") = "Yes" Then Sheets(Format(Now, "mmmm")).Activate Range("A1").Select Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False End If End Sub

因此,请检查今天是一个月的第一天还是第二天。如何消除引用G1的需要,而是直接将公式应用于VBA?

非常感谢

3 个答案:

答案 0 :(得分:2)

尝试

If Evaluate("=IF(OR(TODAY()=WORKDAY(EOMONTH(TODAY(),-1),1,0),TODAY()=WORKDAY(EOMONTH(TODAY(),-1),2,0)),""Yes"",""No"")") = "Yes" Then 

感谢@jeeped帮助我将其重新表达为:

If Evaluate("OR(TODAY()=WORKDAY(EOMONTH(TODAY(),-1),1,0),TODAY()=WORKDAY(EOMONTH(TODAY(),-1),2,0))") Then 

答案 1 :(得分:2)

尝试

if Date = application.workday(dateserial(year(date), month(date), 0), 1) or _
   Date = application.workday(dateserial(year(date), month(date), 0), 2) then
    debug.print "1st or 2nd workday of month"
end if

一个月的第0天是上个月的EOMONTH。

答案 2 :(得分:2)

一种不使用工作表功能的方法:

Function WorkdayOfMonth(ByVal dtInput As Date) As Integer
    Dim dt As Date
    Dim i As Integer
    If Weekday(dtInput, vbMonday) < 6 Then
        For dt = DateSerial(Year(dtInput), Month(dtInput), 1) To dtInput Step 1
            If Weekday(dt, vbMonday) < 6 Then i = i + 1
        Next dt
        WorkdayOfMonth = i
    Else
        WorkdayOfMonth = 0
    End If
End Function

Sub Test()
    If WorkdayOfMonth(Date) > 0 and WorkdayOfMonth(Date) <= 2 Then
        'do stuff
    End If
End Sub