繁体   English   中英

Excel VBA:“将子程序改为函数”,用于字符串转换

[英]Excel VBA: "Change a Subroutine into a Function", for String Conversion

通过我的工作,并复制其他人,我拼凑了一个 Excel VBA Sub,它将一个长串与(文本组)和(数字组)的组分隔成一个替换字符串,每个单独的组之间有空格; 按照这个例子: • “123abc12aedsw2345der” • ...应用选择 Sub() 然后变成: • “123 abc 12 aedsw 2345 der”它根据“选择”转换原始单元格中的字符串,所以我目前只剩下更改后的数据是原始单元格问题:我想将其更改为 FUNCTION,其中转换后的数据将出现在 Function 单元格中,并保持原始单元格完好无损。 我已经完成了数百个,但我似乎无法让它作为一个独立的 FUNCTION 工作。在完成和工作的子例程下面,我试图转换为一个独立的 function 以从工作表上的任何地方调用:

Sub SplitTextNumbersSelection()
Dim c As Range

'********** Inserts Space Before Number Groups ******************************
For n = 1 To 10
    For Each c In Selection
        c = InsertSpace(c.Text)
    Next
Next n
'****************Inserts Space Before Letter Groups ***********************
For n = 1 To 10
    For Each c In Selection
        c = InsertSpace2(c.Text)
    Next
Next n
'****************************************

End Sub

Function InsertSpace(str As String) As String
    With CreateObject("vbscript.regexp")
        .Pattern = "([a-z])(\d)"
        '.Pattern = "(\d)([a-z])"
        InsertSpace = .Replace(str, "$1 $2")
    End With
End Function

Function InsertSpace2(str As String) As String
    With CreateObject("vbscript.regexp")
        '.Pattern = "([a-z])(\d)"
        .Pattern = "(\d)([a-z])"
        InsertSpace2 = .Replace(str, "$1 $2")
    End With
End Function

简单一点:

Function PrepString(v As String)
    Dim rv As String, i As Long, c1, c2
    For i = 1 To Len(v) - 1
        c1 = Mid(v, i, 1)
        c2 = Mid(v, i + 1, 1)
        If (c1 Like "[a-z]" And c2 Like "[0-9]") Or _
           (c2 Like "[a-z]" And c1 Like "[0-9]") Then
            rv = rv & c1 & " "
        Else
            rv = rv & c1
        End If
    Next i
    PrepString = rv & Right(v, 1)
End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM