2015-02-23 94 views
0

背景信息: 我想测试未来日期以检查它们是否在周一,周三或周六。如果日期符合三个标准之一,则日期将返回到单元格中。我设法解决了这个问题。Excel VBA函数做循环和测试标准

问题:我希望函数自动循环45天,而不是仅从第一个日期引用。

问题

  • 有没有更有效的方法或更合适的方法来写代码?
  • 是否有可能在函数中执行循环?是的,你能展示并解释
  • 什么是其他可能的方法?我正在扩大我的知识,请分享:)

谢谢你的时间!

Public Function AFPSECONDOFFDAY(NextOffDay As Date) As String 
Dim ans As String, dayCount As Integer, n As Integer 

n = 2 

' This statement returns the date into the cell if it is Monday, Wednesday or Saturday 

If Format(NextOffDay + 2, "w", vbMonday) = 1 _ 
Or Format(NextOffDay + 2, "w", vbMonday) = 3 _ 
Or Format(NextOffDay + 2, "w", vbMonday) = 6 Then 
' would like it to continue for another 45 days instead 
' of stopping after + 2 days 
    AFPSECONDOFFDAY = NextOffDay + 2 

Else 
    'If the date does not meet the criteria, I would like it to _ 
    skip and do the next date. So that cells will be filled simultaneously. 
    AFPSECONDOFFDAY = "" 

End If 

End Function 
+0

获得这个循环是很容易的部分。您希望如何返回这些信息?你是否想要将所有日期返回到输入的单元格中? – Kyle 2015-02-23 16:34:53

+0

请继续向右偏移至最后。第一个单元格,第二个单元格和之后:) – Kelvinlimjk 2015-02-23 16:46:28

回答

0

我将这个函数嵌套在子过程中。下面的循环遍历45天(这些45中包含NextOffDay),并将工作簿中第一个工作表的第1行中的下一个打开单元格写入代码写入的工作簿中的每个日期。

Public Function AFPSECONDOFFDAY(NextOffDay As Date) As String 
Dim ans As String, dayCount As Integer, n As Integer 

n = 2 

' This statement returns the date into the cell if it is Monday, Wednesday  or Saturday 

If Format(NextOffDay + 2, "w", vbMonday) = 1 _ 
Or Format(NextOffDay + 2, "w", vbMonday) = 3 _ 
Or Format(NextOffDay + 2, "w", vbMonday) = 6 Then 
' would like it to continue for another 45 days instead 
' of stopping after + 2 days 
    AFPSECONDOFFDAY = NextOffDay + 2 

Else 
    'If the date does not meet the criteria, I would like it to _ 
    skip and do the next date. So that cells will be filled simultaneously. 
    AFPSECONDOFFDAY = "" 

End If 

End Function 

Sub Func_Loop() 
Dim NextOffDay as Date 
Dim i as Integer 

Call Different_Sub 'You simply write Call and the name of the sub procedure. 
        'If it is in a different module, you must qualify which module 
        'If there is an argument it would be: Call Different_Sub(argument) 

NextOffDay = "02/25/2015" 'Change this date to whatever you need, or have a user enter the date through an input box or set it to a certain cell. 

For i = 0 to 44 
If AFPSECONDOFFDAY(NextOffDay + i) <> "" then 
    Thisworkbook.Worksheets(1).Cells(1,columns.count).end(xltoleft).offset(0,1) = AFPSECONDOFFDAY(NextOffDay + i) 
End if 
Next i 
End Sub 
+0

子过程不能灵活工作,并且它从1900年返回日期。你可以在函数中插入循环吗?我希望这个函数能够只返回在接下来的45天内的星期一,星期三或星期六的日期。无论如何,感谢您的努力! – Kelvinlimjk 2015-02-24 13:00:26

+0

我在上面发布的代码中看到了问题,并且可以修复日期问题。循环可以进入函数内部,但是它会在一个单元格中返回一个长字符串,这就是你想要的吗? – Kyle 2015-02-24 15:06:26

+0

我喜欢你使用inputbox的想法。它可以在一个单元格中有每个日期吗?你能教我如何编写识别空单元格并删除列吗?谢谢! – Kelvinlimjk 2015-02-25 07:11:49