2016-05-16 29 views
0

使用excel-Access VBA環境。 excel頁面中的vba代碼將日期單元格的值分配給日期過濾器。由於我總是以巴拿馬語區域的格式使用dd/mm/yyyy格式,因此代碼在12日之後的日期中工作正常(意思是指定月份時沒有歧義),但在日期少於13天時,它會將日期轉換爲數字值,並且我收到一條錯誤消息,說42502(例如,可能爲2012年12月)不是過濾器的有效值。當一天過去12日,它工作正常。我如何捕獲這個錯誤並解決它?動態表格值過濾器中的日期轉換錯誤

代碼:

ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh 

    ' Range R1 contains the value we desire to filter the date of dynamic table 

    ' Range B1 contains the date filter of the dynamic table  

    Range("B1").Select 

    ActiveSheet.PivotTables("PivotTable1").PivotFields("fecha").ClearAllFilters 

    Application.ScreenUpdating = False 
    'ActiveSheet.Range("B1") = Range("R1").Value 
    ff = Range("R1").Value 
    ActiveSheet.Range("B1") = Right("00" & Day(ff), 2) & "/" & Right("00" & Month(ff), 2) & "/" & Year(ff) 
    Application.ScreenUpdating = True 

這是在許多方面伊夫試圖解決這一個,但只有本月12日之後適用於天

+0

歡迎堆棧溢出 - 你可以請把你的代碼,這樣我們就可以理解它實際上是做什麼的? –

+0

ActiveSheet.PivotTables(「PivotTable1」)。PivotCache.Refresh 「範圍R1包含我們的願望來過濾動態表 的日期」的值範圍B1包含動態表\t 範圍(「B1」)的日期濾波器。選擇 ActiveSheet.PivotTables( 「PivotTable1」)。透視字段( 「出生日期」)。ClearAllFilters Application.ScreenUpdating =假 「ActiveSheet.Range( 「B1」)=範圍( 「R1」)。值 FF =範圍(」 R1「)。值 ActiveSheet.Range(」B1「)= Right(」00「&Day(ff),2)&」/「&Right(」00「&Month(ff),2)&」/「 &Year(ff) Application.ScreenUpdating = True – georgepty

+1

請使用代碼編輯您的原始文章,而不是在評論中,因爲它是不可讀的。 –

回答

1

,如果你發佈了一些代碼,這將是有益的,但我相信問題是你需要在代碼中指定你使用的是什麼格式,而不是讓VBA爲你猜。由於Microsoft是一家美國公司,我們使用MM/DD/YYYY格式,因此可能默認採用美國格式,但當它達到13日時,默認情況下爲非美國格式。

+0

這真的是一個評論,因爲它只是說明爲什麼,而不是如何克服。 –

0

試試這個:

Dim lastRow, i As Long 
Dim datStg As String 

lastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 

For i = 2 To lastRow 
    dateStg = Cells(i, "R").Text 
    If datStg <> "" Then 
     Cells(i, "B").Value = DateSerial(Mid(dateStg, 8, 4), Mid(dateStg, 5, 2), Mid(dateStg, 2, 2)) 
     Cells(i, "B").NumberFormat = "dd/mm/yyyy" 
    End If 
Next i