2017-02-13 19 views
0

我正在開發一個擁有所有月份數據的excel。如果我必須在我目前的工作月後才過濾幾個月。那麼如何編寫相同的編碼。僅篩選下月

例如,現在我在2017年2月份工作。我想過濾到2月17日。排除未來所有個月Feb'17

我的代碼

ActiveSheet.Range("$A$:$AA" & LastRow2).AutoFilter FIELD:=18, Criteria1:=">=01/01/2006",Criteria2:="<=28/02/2017" 
+0

聽起來像的俯視圖。現在,如果你會如此友好地分享你的代碼嘗試,你需要我們的幫助,我們將盡我們所能幫助你 –

+0

我的代碼如下 - ActiveSheet.Range(「$ A $:$ AA」&LastRow2) .AutoFilter FIELD:= 18,Criteria1:=「> = 01/01/2006」,Criteria2:=「<= 28/02/2017」 – Saran

+0

'ActiveSheet.Range(「A1:AA」&LastRow2).AutoFilter FIELD: = 18,Criteria1:=「> = 01/01/2006」,操作員:= xlAnd,Criteria2:=「<= 28/02/2017」' – user3598756

回答

0

後的criteria2你可以得到由date()函數的今天日期將其轉換爲字符串使用MID()得到的只有年份和月份值...寫如果基於月份值函數來獲得最後的日期值....添加函數來檢查一年的飛躍,並添加日期值二月

Month_1=datepart("m",date()) 
year_1=datepart("yyyy",date()) 
if month in (01,03,05,07,08,10,12) then 
last_day=31 
elseif month <> 02 then 
last_day=30 
else 
isLeapYear = (Month(DateSerial(Yr, 2, 29)) = 2) 
if isLeapYear = True then 
last_day=29 
else 
last_day=28 
end if 
end if 
criteria_2=cdate(last_day & "/" & Month_1 & "/" & year_1) 

添加此變量作爲條件2在你的過濾器....你總是會得到當前月份的最後一天代碼。

我還沒有測試過代碼。請原諒我,如果它有錯誤。

+0

答案使用DateSerial,一個月的最後一天實際上是下個月的第0天。例如,爲了獲得2月份的最後一天,你可以使用'DateSerial(2017,3,0)'。爲了獲得當月的最後一天,你可以使用'DateSerial(Year(now),Month(now)+1,0)'。 –

0

您可以嘗試使用WorksheetFunction.EoMonth獲取當前月份(或任何其他日期)的最後一天。

此外,請儘量遠離ActiveSheet並改用完全限定的對象。

注意:與我的測試我發現,如果我使用Criteria2:="<=" & Cdbl(toDate)它的作品。當我試着沒有鑄造Cdbl它沒有(因爲我的單元格的日期格式),在你的情況下,你可能不需要它。

代碼示例

Option Explicit 

Sub FilterNextTwoMonths() 

Dim toDate As Date 

' get the last date of the current month 
toDate = WorksheetFunction.EoMonth(Date, 0) 

With Worksheets("Sheet1") '<-- replace "Sheet1" with your sheet's name 
    .Range("$A$:$AA" & LastRow2).AutoFilter Field:=18, Criteria1:=">=01/01/2006", Operator:=xlAnd, Criteria2:="<=" & CDbl(toDate)  
End With 

End Sub