簡體   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