简体   繁体   中英

How to combine multiple rows from a spreadsheet into one, if the value at a specific position of a string matches, in Excel, using VBA?

How to combine multiple rows in sequence from a spreadsheet into one, if the value at a specific position of a string matches? The value required to match is between the last 2 hyphens of filename.

Example 1:

<img src="abcd-efgh-1234-567.jpg">
<img src="ijklmn-opqrst-1234-9876.jpg">
<img src="aabb-ccd-eeffgh-1234-000.jpg">

to:

<img src="abcd-efgh-1234-567.jpg"><img src="ijklmn-opqrst-1234-9876.jpg"><img src="aabb-ccd-eeffgh-1234-000.jpg">

Example 2:

<img src="abcd-efgh-432-567.jpg">
<img src="ijklmn-opqrst-432-9876.jpg">
<img src="aabb-ccd-eeffgh-765-000.jpg">
<img src="aabb-ccd-eeffgh-3210-000.jpg">
<img src="aabb-ccd-eeffgh-987-567.jpg">
<img src="aabb-ccd-eeffgh-987-7657.jpg">

to:

<img src="abcd-efgh-432-567.jpg"><img src="ijklmn-opqrst-432-9876.jpg">
<img src="aabb-ccd-eeffgh-765-000.jpg">
<img src="aabb-ccd-eeffgh-3210-000.jpg">
<img src="aabb-ccd-eeffgh-987-567.jpg"><img src="aabb-ccd-eeffgh-987-7657.jpg">
Function ImgCombine(ByVal imgStringArray As Variant) As Variant
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")

    Dim img As Variant
    Dim key As String
    Dim tempArray As Variant
    For Each img In imgStringArray
        if img like "*-*-*" then
            tempArray = Split(img, "-")
            key = tempArray(UBound(tempArray) - 1)
            dict(key) = dict(key) & img
        end if
    Next img

    ImgCombine = dict.Items()

    Set dict = Nothing
End Function

This code assumes that imgStringArray contains valid elements. Checks can be added. You can try the function like bellow (for example 1)

Sub test()
    dim m
    m = ImgCombine(Array("<img src=""abcd-efgh-1234-567.jpg"">", _
                     "<img src=""ijklmn-opqrst-1234-9876.jpg"">", _
                     "<img src=""aabb-ccd-eeffgh-1234-000.jpg"">"))
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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