2013-12-18 52 views
-3

日期我想獲得的星期五日期爲當月 這是我心目中:獲取週五在VBA

functionFindFriday() 
if 1st friday then functionFindFriday = '6 dec 2013' 
if 2nd friday then functionFindFriday = '13 dec 2013' 
if 3rd friday then functionFindFriday = '20 dec 2013' 
if 4th friday then functionFindFriday = '20 dec 2013' 
end function 

,我想用

functionFindFriday(1)它會顯示叫它'2013年12月6日'

functionFindFriday(2)它將顯示'13 2013' 年12月

+2

請包括嘗試的解決方案,爲什麼他們沒有工作!查看「Application.WorksheetFunction.Weekday」作爲起點! –

+0

感謝您的輸入 – Xarxas

+0

簡單公式:= TODAY() - DAY(TODAY())+ 8-WEEKDAY(TODAY() - DAY(TODAY())+ 2)+(N-1)* 7。在VBA中:findFriday = Date - Day(Date)+ 8 - Weekday(Date - Day(Date),vbFriday)+(N-1)* 7 –

回答

4

這工作:

Function FindFriday(nFriday As Integer) As Date 
    Dim dateFirst As Date 
    Dim dateNthFriday As Date 
    dateFirst = DateSerial(Year(Now), Month(Now), 1) 
    dateNthFriday = DateAdd("d", 7 * nFriday - Weekday(dateFirst, vbSaturday), dateFirst) 
    If DateSerial(Year(dateNthFriday), Month(dateNthFriday), 1) <> dateFirst Then _ 
     Err.Raise 9999, , "There aren't " & nFriday & " Fridays in this month." 
    FindFriday = dateNthFriday 
End Function 
+0

你是我的英雄!謝謝! – Xarxas

2

functionFindFriday()

  • 獲取first day of the current month。使用Weekday(that_day)來了解它是哪一天。 (如果that_dayvbTuesday則爲3)。
  • 開始DateAdd以上結果爲7,每次換個星期五,直到下一個結果屬於下個月。
+0

謝謝你的輸入 – Xarxas

相關問題