2017-03-16 54 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將其置於一個模塊中。

此示例返回一個字母的值,但您可以輕鬆修改它以返回整個單詞。