2016-05-16 45 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