'Excel中对带有文本的单元格进行计算 Function CalculateWithText(ParamArray args() As Variant) Dim objFormula AsString Dim result AsString Dim current AsString Dim eachRange As Range ForEach Rng In args ForEach eachRange In Rng If result <> ""Then result = result + "+" EndIf result = result + CStr(CalculateText(eachRange.Value)) Next result = CStr(Evaluate(result)) Next Debug.Print result CalculateWithText = Evaluate(result) EndFunction
Function CalculateText(objFormula AsString) Dim current AsString Dim validSymbol AsString validSymbol = "+,-,*,/,.,(,)" '替换换行符、空格等 objFormula = Replace(objFormula, vbNewLine, "+") objFormula = Replace(objFormula, vbCr, "+") objFormula = Replace(objFormula, vbLf, "+") objFormula = Replace(objFormula, vbCrLf, "+") objFormula = Replace(objFormula, " ", "+") '替换中文(、) objFormula = Replace(objFormula, "(", "(") objFormula = Replace(objFormula, ")", ")") For n = 1To Len(objFormula) current = Mid(objFormula, n, 1) If IsNumeric(current) Or IsInArray(current, Split(validSymbol, ",")) Then result = result + current EndIf Next n 'Fix当单元格为空时Error 2015,为空设置结果为0 If result <> ""Then CalculateText = Evaluate(result) Else CalculateText = 0 EndIf EndFunction
Function IsInArray(stringToBeFound AsString, arr As Variant) AsBoolean IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) EndFunction