2017-03-16 51 views
0

如何用Excel中的字母计算相关数字的总和? 数据在下面提到。 我为每个字母指定了一些值。用字母计算数字的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中输入任何文字,就必须回到个位数。

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

我们该如何做到这一点?

+2

为什么会的1,2,5,1和9的总和为9敏感?你是什​​么意思“等等” - 我看不出你提供的字母和它们相应的值之间的任何关系,那么我们如何知道应该与其他字母相关联的值呢? – YowE3K

+0

我想你可以使用命名值(与命名范围相同,除了它们引用静态值),但不能使用'C'或'R'作为名称和可能的其他字母。然后你可以使用'= SUM(A,B,D,H)'来返回13. –

+0

我给每个字母指定了一些值。 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中输入任何单词,它必须返回单个数字。 例如,单词“google”的总和是(3 + 7 + 7 + 3 + 3 + 5)= 28 = 10 = 1最终结果。 –

回答

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

这个问题太广泛了 - 但我喜欢你的答案......唯一的是你不做OP最后一步将28转换为1的'google'例子。例如。 28 = 1,因为“2 + 8 = 10”和“1 + 0 = 1”。 OP要数字计算器。 –

+0

它的工作。但是如果我输入一些像“wwwwwwwww”这样的词,它会返回54,并且必须返回9. –

+0

我的坏消息没有看到。我更新了我的答案。 @RobinMackenzie,但你是对的,显然这个问题太广泛了。我保证会改进。 –

0

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

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 

你可以在子使用,或作为User Defined Function将其置于一个模块中。

此示例返回一个字母的值,但您可以轻松修改它以返回整个单词。