用字母计算数字的Excelmacros程式

我们如何用excel中的字母计算相关数字的总和? 数据在下面提到。 我为每个字母分配了一些值。

"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"

他们的价值分别是:

1,2,3,4,5,8,3,5,1,1,2,3,4,5,7,8,1,2,3,4,6,6,6,5,1,7

如果我在Excel中input任何单词,它必须返回单个数字。

例如,单词“google”的总和是(3 + 7 + 7 + 3 + 3 + 5)= 28 = 10 = 1的最终结果。

我们怎样才能做到这一点?

将以下代码添加到模块中:

 Sub test() Debug.Print SumChars("ABCd") End Sub Public Function SumChars(strInput As String) As Double Dim arrChar(), arrVals() arrChar = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z") arrVals = Array(1, 2, 3, 4, 5, 8, 3, 5, 1, 1, 2, 3, 4, 5, 7, 8, 1, 2, 3, 4, 6, 6, 6, 5, 1, 7) Dim dblSum As Double dblSum = 0 Dim i As Integer, j As Integer For i = 1 To Len(strInput) For j = LBound(arrChar) To UBound(arrChar) If UCase(arrChar(j)) = UCase(Mid(strInput, i, 1)) Then dblSum = dblSum + arrVals(j) End If Next j Next i Do While Len(CStr(dblSum)) > 1 dblSum = DigitSum(dblSum) Loop SumChars = dblSum End Function Private Function DigitSum(dblValue As Double) As Double Dim i As Integer, dblSum As Double For i = 1 To Len(CStr(dblValue)) dblSum = dblSum + Mid(CStr(dblValue), i, 1) Next i DigitSum = dblSum End Function 

你可以在任何单元格中使用=SumChars("ABC") 。 为了区分大小写,您需要删除UCase

 If arrChar(j) = Mid(strInput, i, 1) Then 

将这些字母放入一个数组中,并将它们的相应值放入一个数组中,然后遍历该数组,直到find所需的字母并从链接的数组中返回其值。

 Function LetterValues(letter As Variant) Dim letters() As Variant, numbers() As Variant letters = Array("A", "B", "C") numbers = Array(1, 2, 3) For x = 0 To UBound(letters) If letters(x) = letter Then LetterValues = numbers(x) Exit Function End If Next x End Function Sub TestFunction() Dim result As Variant result = LetterValues("A") End Sub 

你可以在一个子模块中使用它,或者把它放在一个模块中作为一个用户自定义函数 。

这个例子返回一个字母的值,但你可以很容易地修改它返回一个单词。