【问题标题】:Convert this long Excel date formula into VBA将此长 Excel 日期公式转换为 VBA
【发布时间】:2017-10-21 01:00:58
【问题描述】:

我在下面有这个 Excel 公式;

DATE(LEFT(A1,3),MID(A1,6,1),MID(A1,7,1))

我想将此 Excel 公式转换为 VBA 用户定义函数。

Public Function getDate(input_date As String)
    'code to convert DATE(LEFT(A1,3),MID(A1,6,1),MID(A1,7,1)) to VBA
End Function

这很棘手,因为函数参数内部使用了函数。就像在 DATE 中使用的 LEFT。

编辑:如果可能的话,我想在 VBA 函数中直接使用 Excel 公式,只需进行最少的修改。是否可以在 Excel VBA 中执行此操作?

【问题讨论】:

    标签: vba excel date


    【解决方案1】:

    这与您在 Excel 中所做的事情并没有什么不同,至少就在函数中调用函数而言:

    Public Function getDate(input_date As String) As Date
        getDate = DateSerial(1900 + CInt(Left(input_date, 3)), _
                             CInt(Mid(input_date, 6, 1)), _
                             Cint(Mid(input_date, 7, 1)))
    End Function
    

    CInt 调用不是绝对必要的,VBA 将强制从 Left 和 Mid 返回的表达式为数值,就像 Excel 所做的一样 - 但我喜欢在这类语句中明确显示转换.但是如果你不想要它们,你可以使用下面的,除了DateSerial而不是DATE之外,它与Excel公式基本相同。 (VBA Date 函数只返回今天的日期。)

    Public Function getDate(input_date As String) As Date
        getDate = DateSerial(1900 + Left(input_date, 3), Mid(input_date, 6, 1), Mid(input_date, 7, 1))
    End Function
    

    需要将 1900 添加到年份,因为 Excel 对 VBA 的处理方式不同。 Excel 将 20 年视为 1920,将 104 年视为 2004。VBA 使用窗口方法,其中小于 30 的年被视为 20yy,介于 30 和 99 之间的年被视为 19yy,大于或等于的年100 被视为 0yyy。


    而且,虽然我强烈不鼓励使用它,但您可以使用 Evaluate 在 VBA 中使用完全相同的 EXCEL 公式:

    Public Function getDate(input_date As String) As Variant
        getDate = Evaluate("DATE(LEFT(""" & input_date & """,3),MID(""" & input_date & """,6,1),MID(""" & input_date & """,7,1))")
    End Function
    

    【讨论】:

    • 感谢您的回答。赞成。如果可能的话,我想直接在 VBA 函数中使用 Excel 公式,而只需进行最少的修改。这是因为我已经有许多现有的 Excel 公式。是否可以在 VBA 中执行此操作?
    • @user3848207 好吧,相当于 Excel 的 DATE 是 VBA 的 DateSerial。除此之外,您可以使用相同的公式。我将更新答案以摆脱(可选)CInts。
    • @user3848207 - 公式必须进行其他修改 - 因为您使用的是“yyy”年份,Excel 和 VBA 采用的方法不同,这需要在输入的内容中显式添加 1900日期,以便让 VBA 得出与 Excel 相同的答案。
    【解决方案2】:

    你可以试试这样的……

    Public Function getDate(input_date As String)
        getDate = CDate(Evaluate("DATE(LEFT(" & input_date & ",4),MID(" & input_date & ",5,2),MID(" & input_date & ",7,2))"))
    End Function
    
    Sub Test()
    MsgBox getDate("20170521")
    End Sub
    

    【讨论】:

    • OP 的日期格式很奇怪。我只是在玩Evaluate,如果第 4 和第 5 个字符不是数字,您必须将 input_date 放在双引号内。 (我不知道什么样的日期格式有 3 位数的年份和 1 位数的月份和日期!也许总是 1 月 1 日。)
    • 这对我来说似乎很奇怪,这就是我对字符串函数进行更改的原因。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多