Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

vba - Substitute text Data from two different columns

I want to remove single word from multiple words separated by comma:

I Want a macro that should work for all sheets in workbook.

I have the following data in Column A in Sheet1, Sheet2, Sheet3. The no of rows and data differ for different sheets.

Little Nicobar
Mildera
Mus
Nancowrie
Nehrugram
Pilomilo Island

and Following data in Column Q:

Little Nicobar,Mildera,Mus,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Mus,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Mus,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Mus,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Mus,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Mus,Nancowrie,Nehrugram,Pilomilo Island

Want output in Column R as follows:

Mildera,Mus,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mus,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Nancowrie,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Mus,Nehrugram,Pilomilo Island
Little Nicobar,Mildera,Mus,Nancowrie,Pilomilo Island
Little Nicobar,Mildera,Mus,Nancowrie,Nehrugram

Means i want remove word in column A from Column R.

For this we can use the formula in R1

=TRIM(SUBSTITUTE(Q1,A1,""))

But its only working for R1.

I want a macro that provides the desired output and should work for all sheets. As the different data present in Sheet1, sheet2...sheetn. Help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this

Sub test()
    Dim vDB, vData, vR()
    Dim s As String
    Dim Ws As Worksheet
    Dim i As Long, n As Long
    For Each Ws In Worksheets
        With Ws
            vDB = .Range("a1", .Range("a" & Rows.Count).End(xlUp))
            n = UBound(vDB, 1)
            vData = .Range("q1").Resize(n)
            ReDim vR(1 To n, 1 To 1)
            For i = 1 To n
                s = Replace(vData(i, 1), vDB(i, 1), "")
                s = Replace(s, ",,", ",")
                If Left(s, 1) = "," Then
                    Mid(s, 1, 1) = Space(1)
                End If
                If Right(s, 1) = "," Then
                    Mid(s, Len(s), 1) = Space(1)
                End If
                vR(i, 1) = Trim(s)
            Next i
            .Range("r1").Resize(n) = vR
        End With
    Next Ws
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...