2016-09-19 146 views
2

我已經閱讀了有關UDF #VALUE錯誤的線索,似乎我對VBA不夠了解,無法使用它們,或者我遇到的問題並不相同。VBA UDF Excel 2010 #VALUE

無論採用哪種方式,我都想根據我創建的公式計算出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中

上我已經將不勝感激什麼錯誤(S)的任何援助實施時返回#VALUE錯誤!

謝謝!

編輯:

我想和若塊,以迎合含年齡「>」開頭。例如,8:6和> 8:6。我想我可能會在開始時對搜索結果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 

我不知道如何做「如果」位,也不知道如何把代碼放在下面的評論...先謝謝了!

使用下面的答案解決 - 非常感謝你!

這是允許「:」或「。」的最終代碼。分隔符和 「>」 符號,以及:

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 
+0

'Monthz = Mid(YearsMonths,Colonz + 1,Lengthz - Colonz)'行中的'Lengthz'爲0,因爲您尚未設置數值。 – Comintern

+0

你不想讓它返回一些東西嗎?像'Function TOTALMONTHS(YearsMonths As String)as Long'? –

+0

我希望它返回一個整數量的月份 - 謝謝你我現在就試試這兩個! –

回答

0

嘗試下面的更新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中的單元格需要格式化爲文本)

enter image description here

+0

圖例!非常感謝您的幫助!它現在完美地工作!你的建議非常有幫助,我覺得我學到了很多東西! –

+0

不客氣,謝謝你的回答 –