Excel VBA函数做循环和测试标准

时间:2015-02-23 15:59:27

标签: excel vba loops 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

1 个答案:

答案 0 :(得分:0)

我会将该函数嵌套在子过程中。下面循环执行45天(NextOffDay包含在这45天中)并将每个日期,即周一,周三或周五写入写入代码的工作簿中第一个工作表的第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