VBA 中的字串操作

VBA 中的字串操作

我有一個單列需要拆分為多個,就像 Excel 中的文字到列一樣。然而,有一個小挑戰。傳統的分隔符號不起作用。考慮下面的字串

Original: Domain\Domain Admins Domain2\User Group Domain3\Developers .....(And so on)
Required: Domain\Domain Admins | Domain2\User Group | Domain3\Developers .....(And so on)

所需字串中的管道意味著需要在此處將其拆分並根據字串的長度複製到下一列。

我的 A 欄中有 506 行的清單。我用下面的公式來檢查「\」i B列的出現情況,計數範圍從0-66

=LEN(A2)-LEN(SUBSTITUTE(A2,"\",""))

我需要幫助來編寫以下邏輯程式碼

  1. 在字串中查找“\”
  2. 找到“\”之前的空格並拆分

我使用了以下程式碼,但它沒有達到目的

Range("A1:A506").Select
Selection.TextToColumns 

請幫忙寫一個牢記第 1 點和第 2 點的程式碼。

答案1

儘管我根據您的要求使用了不同的邏輯,但應該這樣做。

您想在空格之前找到 \ ,而我的程式碼只是查找Domain(注意空格)。

Option Explicit

Sub DoThis()

Dim col As Integer
col = 65

Dim splitWord As String
splitWord = "Domain"

Dim row As Integer
row = 1

Do While (Range("A" & row).value <> "")

Dim value As String

value = Range("A" & row).value

Dim values() As String

values = Split(value, " " & splitWord)

Dim firstResult As String

Dim i As Integer

For i = 1 To UBound(values)

firstResult = values(0) ' not efficient but easier code to read

Range(Chr(col + i) & row).value = splitWord & values(i)

Next i

Range(Chr(col) & row).value = firstResult
row = row + 1
col = 65
Loop

End Sub

在此輸入影像描述

在此輸入影像描述

請注意,我稍微更新了一些單字以顯示它正在複製正確的數據,但它也已經用您的範例進行了測試。

在測試之前,請確保先建立資料備份,因為這樣的巨集無法撤銷!

答案2

子 ExtractBySlash()

調暗範圍

Dim subS 作為變體

暗x一樣長

微弱如長

調暗計數器只要

計數器 = 1

對於範圍內的每個 r("a1:a506")

subS = Split(r.Text, "\")

For x = LBound(subS) + 1 To UBound(subS)

    For y = Len(subS(x)) To 1 Step -1

        If Mid(subS(x), y, 1) = " " Then

            r.Offset(0, counter) = subS(x - 1) & "\" & Left(subS(x), y)

            subS(x) = Trim(Right(subS(x), Len(subS(x)) - y))

            counter = counter + 1

            Exit For

        End If

    Next y

Next x

下一個

結束子

相關內容