我想计算一个日期范围与VBA(MS-Access)中的另一个数据范围重叠的程度。
示例:
DateRangeA = 5月1日至15日至3月3日 - 15日 DateRangeB = 3月2日至2月15日至6月20日
我的问题: RangeA有多少是RangeB的一部分(百分比)?
它们也可能根本没有重叠,或者RangeA完全在RangeB内部。
我确信我能够编写代码来执行此操作,但可能很多人已经在我面前执行此操作并测试了他们的代码。
因此,如果你有现成的代码,那么请发布一个答案,但不要只为我做代码。
如果没有人在24小时内回答我的问题,那么我将自己编写代码并发布。
由于
答案 0 :(得分:1)
我假设你的意思是百分之几。
typedef struct button {
char *image_path;
} Button;
typedef struct control_node {
Control *node;
struct control_node *next;
} ControlNode;
typedef struct panel {
ControlNode *children;
} Panel;
typedef union control_data {
Panel panel;
Button button;
} ControlData;
typedef struct control {
int x;
int y;
int type;
ControlData *data;
} Control;
在立即窗口中,您可以像这样测试:
Public Function GetPercentOverlapOfDates(ByVal From1 As Date, ByVal Thru1 As Date, ByVal From2 As Date, ByVal Thru2 As Date) As Double
If (Thru1 < From2) Then
GetPercentOverlapOfDates = 0
Else
Dim lTotalNumberOfDays As Long
lTotalNumberOfDays = DateDiff("d", From1, Thru2)
Dim lTotalNumberOverlap As Long
lTotalNumberOverlap = DateDiff("d", From2, Thru1)
Dim dPercentOverlap As Double
dPercentOverlap = lTotalNumberOverlap / lTotalNumberOfDays
GetPercentOverlapOfDates = dPercentOverlap
End If
End Function
输出:
? Format$(GetPercentOverlapOfDates("5-Jan-15", "7-Mar-15", "3-Feb-15", "20-June-15"), "0.0%")
答案 1 :(得分:0)
这是我认为/希望包含所有可能性的代码:
Function sglGetTestOverlapsMembership(dateMembershipFrom As Date, dateMembershipTo As Date, dateTestFrom As Date, dateTestTo As Date) As Single
Dim sglReturn As Single
If dateMembershipTo < dateTestFrom Then
sglReturn = 0
ElseIf dateTestTo < dateMembershipFrom Then
sglReturn = 0
ElseIf dateTestFrom <= dateMembershipFrom And dateTestTo >= dateMembershipTo Then
sglReturn = 1
ElseIf dateMembershipFrom <= dateTestFrom And dateMembershipTo >= dateTestTo Then
sglReturn = dateDiff("s", dateTestFrom, dateTestTo) / dateDiff("s", dateMembershipFrom, dateMembershipTo)
ElseIf dateTestTo >= dateMembershipFrom And dateTestTo < dateMembershipTo Then
sglReturn = dateDiff("s", dateMembershipFrom, dateTestTo) / dateDiff("s", dateMembershipFrom, dateMembershipTo)
ElseIf dateMembershipTo >= dateTestFrom Then
sglReturn = dateDiff("s", dateTestFrom, dateMembershipTo) / dateDiff("s", dateMembershipFrom, dateMembershipTo)
End If
sglGetTestOverlapsMembership = sglReturn
End Function
这是测试它的方法:
Format$(sglGetTestOverlapsMembership(#5/2/2015#, #9/2/2015#, #6/1/2015#, #7/31/2015 11:59:59 PM#), "0.00%")
几句话:
我没有使用像DateRangeA这样的东西,而是决定使用更多描述性的变量名。我真正想要做的是找出“测试日期范围”中有多少是“会员日期范围”的一部分。
在dateDiff函数中,我没有使用天数,因为它返回0的原因是这样的:dateDiff(&#34; d&#34;,#1/1/2015#,#1/1/2015 23 :59:59#)。使用小时本来已经很好,但我决定使用秒来使其尽可能准确。
我测试了它,但如果您发现代码有问题,请告诉我。