1

我尝试在 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

感谢帮助。

4

2 回答 2

11

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

于 2012-08-21T22:38:06.307 回答
-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

'Com o código abaixo pode-se'remover os espaços extras entre as palavras de um texto: Function 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)

结束功能

于 2015-05-28T03:42:56.480 回答