在Excel /宏中将字符串转换为双精度

时间:2012-08-21 22:19:37

标签: excel vba excel-vba

我尝试在Excel中创建新函数,会计算给定的值(类似于SUM函数,但只有给定的前缀)。

  A
---------    
1|AA30  
2|AA10 
3|BC446 
4|AA10

// result will be 50  on SUM_PREFIX(A1:A4;"AA")

问题是,当值为例如AA10,434或AA4.43时。我可以帮我解决问题吗?这是我在VB中的第一次删除。

 Function SUM_PREFIX(Data As Range, prefix As String) As Double

    Dim result As Double
    Dim strVal As String
    Dim i As Integer
    Dim objRegExp As Object

   Set objRegExp = CreateObject("vbscript.regexp")
   With objRegExp
        .IgnoreCase = True
        .MultiLine = False
        .Pattern = "^[" + prefix + "]+[0-9]+(\,|\.)?[0-9]?$"
        .Global = True
    End With

    For i = 1 To Data.Rows.Count
        Debug.Print Data.Cells(i, 1)
        If objRegExp.Test(Data.Cells(i, 1)) = True Then
            strVal = Replace(Data.Cells(i, 1), prefix, "")
            Debug.Print strVal
            strVal = Trim(Replace(strVal, ",", "."))
            Debug.Print strVal
            result = result + CDbl(strVal)
        End If
    Next i

    SUM_PREFIX = result
End Function

感谢您的帮助。

2 个答案:

答案 0 :(得分:10)

CDbl可识别区域设置,因此请检查您的Replace是否正确(例如,在我的区域设置中,我必须将“。”替换为“,”才能使其正常工作) 。 如果您不想依赖区域设置感知代码,请使用Val代替CDbl,因为Val仅识别“。”作为有效的小数分隔符而不管语言环境。

答案 1 :(得分:-1)

Function SUM_PREFIXO(DADOS As Range, PREFIXO As String) As Double

Dim result, NI As Double
Dim strVal As String
Dim i As Integer
Dim objRegExp As Object



   Set objRegExp = CreateObject("vbscript.regexp")
   With objRegExp
        .IgnoreCase = True
        .MultiLine = False
        .Pattern = "^[" + PREFIXO + "]+[0-9]+(\,|\.)?[0-9]?$"
        .Global = True
    End With

    NI = DADOS.Rows.Count

    For i = 1 To DADOS.Rows.Count

    Debug.Print (DADOS.Cells(i, 1))

    If objRegExp.Test(RetiraEspaço(DADOS.Cells(i, 1))) = True Then
        strVal = Trim(Replace(DADOS.Cells(i, 1), PREFIXO, ""))
        Debug.Print strVal
        strVal = Trim(Replace(strVal, ".", ","))
        Debug.Print strVal
        strVal = Trim(Replace(strVal, ",", ","))
        Debug.Print strVal
        result = result + CDbl(strVal)

    End If
    Next i

SUM_PREFIXO = result
End Function

'Comocódigoabaixopode-se 'removerosespaçosalssentre as palavras de um texto: 功能RetiraEspaço(Texto)

Dim Vpalavra, inicio, termino, Wresultado
inicio = 1
Texto = UCase(Texto) & " "

Do Until InStr(inicio, Texto, " ") = 0
    termino = InStr(inicio, Texto, " ")
    Vpalavra = Mid(Texto, inicio, termino - inicio)
    inicio = termino + 1

    Wresultado = Wresultado & "" & Vpalavra
Loop

RetiraEspaço = Trim(Wresultado)

结束功能