gpt4 book ai didi

vba - 将此长 Excel 日期公式转换为 VBA

转载 作者:行者123 更新时间:2023-12-04 21:21:42 24 4
gpt4 key购买 nike

我在下面有这个 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 中执行此操作?

最佳答案

这与您在 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 之外,它与 Excel 公式基本相同。而不是 DATE . (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。

而且,虽然我会 强烈 不鼓励使用它,您可以在 VBA 中使用完全相同的 EXCEL 公式,使用 Evaluate :
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 日期公式转换为 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com