我正在尝试为此目的创建功能:我有一年的出生名单,我想要拿出当年的最后两个数字并总结它们。如果这个总和小于10,那将是我需要的结果。如果结果大于10(例如:9 + 9 = 18),我将把这两个数字(1和8)分开并得到它们的总和(1 + 8 = 9。这小于10,所以它会是我的结果)
这是我的代码,但它只给我第一次拆分和求和的结果(本例中为18):
Function test(yob as range) as integer
Dim sum, i, j, i2, j2 as integer
i = mid(yob, 3, 1)
j = right(yob, 1)
sum = i + j
If sum < 10 then
test = sum
Else:
i2 = left(sum, 1)
j2 = right(sum, 1)
test = i2 + j2
End If
End function
答案 0 :(得分:2)
Sub test()
Debug.Print getSum(9, 9)
'/ Prints 9
Debug.Print getSumShort(7, 7)
'/ Prints 5
End Sub
Public Function getSum(x As Long, y As Long)
Dim res As Long
res = x + y
Do While res > 10 '/ Keep repeating till its greater than 10
res = (res \ 10) + (res Mod 10)
Loop
getSum = res
End Function
'/ Another way using 9 as divider.
Public Function getSumShort(x As Long, y As Long)
Dim res As Long
res = (x + y) Mod 9
getSum = IIf(res = 0, 9, res)
End Function
答案 1 :(得分:0)
Function sum2d(year)
sum2d=IIf(year mod 100, (year - 1) Mod 9 + 1, 0)
End Function
Sub Test
For Each v in Array(1980, 2001, 2017)
Debug.Print v; "=>"; sum2d(v)
Next
Next