繁体   English   中英

VBA UDF Excel 2010 #VALUE

[英]VBA UDF Excel 2010 #VALUE

我已经阅读了有关UDF #VALUE错误的线程,似乎我对VBA的了解不足以使用它们,或者我遇到的问题不一样。

无论哪种方式,我都试图创建一个UDF以根据我创建的公式以YY:MM格式计算年龄中的月数。

Function TOTALMONTHS(YearsMonths As String)
Colonz = WorksheetFunction.Find(":", YearsMonths)
Yearz = Left(YearsMonths, Colonz - 1)
Monthz = Mid(YearsMonths, Colonz + 1, Lengthz - Colonz)
Lengthz = Len(YearsMonths)
TOTALMONTHS = Yearz * 12 + Monthz
End Function

在Excel 2010中实施时,以上代码返回#VALUE错误。

对于我犯了什么错误,我们将给予任何帮助!

谢谢!

编辑:

我正在尝试使用If块,以适应开头包含“>”的年龄段。 例如8:6和> 8:6。 我想我一开始可能会对search = 1结果产生误判,但无法弄清楚原因。

Function TOTALMONTHS(YearsMonths As String) As Integer
If WorksheetFunction.Search(">", YearsMonths) = 1 Then
Greaterz = 2
Else
Greaterz = 1
End If
Colonz = WorksheetFunction.Find(":", YearsMonths)
Yearz = Mid(YearsMonths, Greaterz, Colonz - Greaterz)
monthz = Right(YearsMonths, Len(YearsMonths) - Colonz)
TOTALMONTHS = Yearz * 12 + monthz
End Function

我不知道如何执行“ If”位,也无法弄清楚如何在下面的注释中添加代码...预先感谢!

解决了以下答案-非常感谢!

这是允许使用“:”或“。”的最终代码。 分隔符和“>”符号:

Function TOTALMONTHS(YearsMonths As String) As Integer

Dim Colonz As Integer, Yearz As Integer, monthz As Integer, Greaterz As Integer

' check if the stings consists of ">" sign
If InStr(YearsMonths, ">") >= 1 Then
    Greaterz = 2
Else
    Greaterz = 1
End If

' check position of ":" or "." sign
If InStr(YearsMonths, ":") >= 1 Then
    Colonz = InStr(YearsMonths, ":")
Else
    Colonz = InStr(YearsMonths, ".")
End If

Yearz = Mid(YearsMonths, Greaterz, Colonz - Greaterz)
monthz = Right(YearsMonths, Len(YearsMonths) - Colonz)
TOTALMONTHS = Yearz * 12 + monthz

End Function

请尝试以下更新的UDF代码:

Function TOTALMONTHS(YearsMonths As String) As Integer

Dim Colonz As Integer, Yearz As Integer, monthz As Integer, Greaterz As Integer

' check if the stings consists of ">" sign
If InStr(YearsMonths, ">") >= 1 Then
    Greaterz = 2
Else
    Greaterz = 1
End If

' check position of ":" sign
Colonz = InStr(YearsMonths, ":")

Yearz = Mid(YearsMonths, Greaterz, Colonz - Greaterz)
monthz = Right(YearsMonths, Len(YearsMonths) - Colonz)
TOTALMONTHS = Yearz * 12 + monthz

End Function

在下面,您可以找到我测试此UDF代码的数据样本:

(请记住,B和E列中的单元格需要设置为文本格式)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM