如何用vba获取沪深A股的所有交易日的日期?

A股的交易日规定为凡是法定节假日和周末都不算交易日,其它日期都算交易日。

基于以上的知识,可以使用如下的代码获取2018年整年的沪深A股的所有交易日的日期:

Sub QQ1722187970()
    Dim dStart As Date
    Dim dEnd As Date
    dStart = VBA.DateSerial(Year(Now()), 1, 1)
    dEnd = VBA.DateSerial(Year(Now()), 12, 31)
    Dim arr() As Date
    dHoliday = Array(#1/1/2018#, #2/15/2018#, #2/16/2018#, #2/19/2018#, #2/20/2018#, #2/21/2018# _
     , #4/5/2018#, #4/6/2018#, #4/30/2018#, #5/1/2018#, #6/18/2018#, #9/24/2018# _
    , #10/1/2018#, #10/2/2018#, #10/3/2018#, #10/4/2018#, #10/5/2018#)
    For i = dStart To dEnd
        If UBound(VBA.Filter(dHoliday, i)) >= 0 Or Weekday(i, vbMonday) > 5 Then
        Else
            ReDim Preserve arr(k)
            arr(k) = i
            k = k + 1
        End If
    Next i
End Sub

以上代码将把所有交易日期存储在arr数组中。

如果想要做成一个函数的,可以使用如下的代码:

Function GetAllDate()
    Dim dStart As Date
    Dim dEnd As Date
    dStart = VBA.DateSerial(Year(Now()), 1, 1)
    dEnd = VBA.DateSerial(Year(Now()), 12, 31)
    Dim oDicDate As Object
    Set oDicDate = CreateObject("Scripting.Dictionary")
    dHoliday = Array(#1/1/2018#, #2/15/2018#, #2/16/2018#, #2/19/2018#, #2/20/2018#, #2/21/2018# _
     , #4/5/2018#, #4/6/2018#, #4/30/2018#, #5/1/2018#, #6/18/2018#, #9/24/2018# _
    , #10/1/2018#, #10/2/2018#, #10/3/2018#, #10/4/2018#, #10/5/2018#)
    For i = dStart To dEnd
        If UBound(VBA.Filter(dHoliday, i)) >= 0 Or Weekday(i, vbMonday) > 5 Then
        Else
            oDicDate.Add i, k
        End If
    Next i
    GetAllDate = oDicDate.keys
End Function

函数的返回值是所有交易日期的数组。

       

发表评论