用字母计算数字的Excel宏公式

时间:2017-03-16 07:23:16

标签: excel excel-vba vba

我们如何用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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

您可以在sub中使用它,或者通过将其放在模块中作为User Defined Function

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