2011-06-13 80 views
0

下面的代码产生错误的结果。在工作表上,我们使用了两种相同的日期格式(dd/mm/yyyy),但是在运行以下时似乎试图将rev_date解释为美国日期格式,而将grid_date解释为正确的英国格式。VBA SUMIF对日期感到困惑 - 产生不正确的结果

我们通过将工作表上的rev_date更改为美式格式来测试这种情况,在这种情况下,它会产生正确的结果。

任何想法,为什么我们需要将rev_date更改为美式格式,我们宁愿保留它作为英国?

Public Function GRIDSALES(rev_date As Date, grid_date As Date) As Double 


    Dim Order_Type As Range 
    Dim Final_Price As Range 
    Dim PaidAlt As Range 
    Dim Excl_Rev As Range 
    Dim PAmount1 As Range 
    Dim PMethod1 As Range 
    Dim PAmount2 As Range 
    Dim PayDate2 As Range 
    Dim PMethod2 As Range 
    Dim Vstatus As Range 
    Dim Team As Range 

    Application.Volatile (True) 

    Set Order_Type = Sheets("KRONOS").Range("$D:$D") 
    Set Final_Price = Sheets("KRONOS").Range("$H:$H") 
    Set PaidAlt = Sheets("KRONOS").Range("$I:$I") 
    Set Excl_Rev = Sheets("KRONOS").Range("$K:$K") 
    Set PAmount1 = Sheets("KRONOS").Range("$O:$O") 
    Set First_PD = Sheets("KRONOS").Range("$Q:$Q") 
    Set PMethod1 = Sheets("KRONOS").Range("$R:$R") 
    Set PAmount2 = Sheets("KRONOS").Range("$T:$T") 
    Set PayDate2 = Sheets("KRONOS").Range("$V:$V") 
    Set PMethod2 = Sheets("KRONOS").Range("$W:$W") 
    Set Vstatus = Sheets("KRONOS").Range("$DL:$DL") 
    Set Team = Sheets("KRONOS").Range("$DO:$DO") 

      GRIDSALES1 = Application.WorksheetFunction.SumIfs(_ 
      PAmount1 _ 
      , Team, "<>9" _ 
      , Vstatus, "<>rejected", Vstatus, "<>unverified" _ 
      , Excl_Rev, "<>1" _ 
      , PMethod1, "<>Credit" _ 
      , PMethod1, "<>Amendment" _ 
      , PMethod1, "<>Pre-paid" _ 
      , First_PD, ">=" & rev_date _ 
      , First_PD, "<=" & Application.WorksheetFunction.EoMonth(grid_date, 0)) 

      GRIDSALES = GRIDSALES1 

端功能

回答

4

当你做到这一点

First_PD, ">=" & rev_date 

First_PD, "<=" & Application.WorksheetFunction.EoMonth(grid_date, 0)) 

你是隐强迫型Daterev_dategrid_date)的两个变量为String类型。隐性强制是不好的做法,这是一个很典型的例子,为什么这是不好的做法。您的日期应使用明确的格式明确转换为String,例如2011

First_PD, ">=" & Format$(rev_date,"dd mmm yyyy") 

在这种格式,1月12日无法与12月1日2011年

+0

+1:关于隐性强制的良好教育解释。 – 2011-06-14 12:07:47

1

我不知道究竟为什么日期格式的变化,但在过去的google搜索,我相当肯定,VBA将解释日期作为美国的这可能是问题。

在你的功能,你可以采取每个日期,并尝试格式为英国日期格式?例如:

Public Function GRIDSALES(rev_date As Date, grid_date As Date) As Double 

Dim d1 as Date, d2 as Date 

d1 = CDate(Format(rev_date, "dd-mm-yyyy")) 
d2 = CDate(Format(grid_date, "dd-mm-yyyy")) 

///rest of your code here... 

End Function 
+0

感谢这个,虽然他们都工作,我选择上面的一个作为主要的答案。这可能稍微简单一些。 – James 2011-06-14 11:23:09

+0

@詹姆斯:没问题。很高兴你得到了适合你的情况的东西 – 2011-06-14 12:08:18

0

由于混淆,我的错误是正义的。

但我解决它像这样

fil1 = "<=" & Month(rev_date) & "/" & Day(rev_date) & "/" & Year(rev_date) 
+0

请格式化您的代码以获得更好的阅读效果 – Moes 2014-07-15 13:43:27