UDF to concatenate values

前端 未结 2 808
深忆病人
深忆病人 2021-01-15 13:09

I am trying to build a user defined function using VBA for excel. That would concatenate a list of stores which has a x mark in that row.

   Store1 Store2 St         


        
相关标签:
2条回答
  • 2021-01-15 13:33

    Another way to achieve is as below. You can do any where in sheets

    Sub Main()
        Call getlistofstores(Range("G13:L15"), Range("G12:L12"))
    End Sub
    
    Function getlistofstores(stores As Range, listofstores As Range)
        Application.Volatile
        Dim fullconcatstring As String
        Dim row As Integer
        Dim column As Integer
        a = stores.Count / listofstores.Count
        b = listofstores.Count
        row = stores.Cells(1).row
        column = stores.Cells(1).column + (b)
        For i = 1 To a
            For j = 1 To b
                If stores.Cells(i, j) = "x" Then
                    If concatstring <> "" Then
                        concatstring = concatstring & ", " & listofstores.Cells(j)
                    Else
                        concatstring = listofstores.Cells(j)
                    End If
                End If
            Next j
            fullconcatstring = fullconcatstring & Chr(10) & Chr(11) & concatstring
            concatstring = ""
        Next i
        Call concatenateallstores(row, column, fullconcatstring)
    End Function
    
    Sub concatenateallstores(r As Integer, c As Integer, d As String)
        str1 = Split(d, Chr(10) & Chr(11))
        str2 = UBound(str1)
        For i = 1 To str2
            Cells(r, c) = str1(i)
            r = r + 1
        Next i
    End Sub
    

    0 讨论(0)
  • 2021-01-15 13:51

    Short but intricate.

    1. uses Evaluate to return an array of matches (Store numbers v x)
    2. Filter removes the non-matches ("V")
    3. Join to make the string from the final array of matches

    UDF

    Function Getx(Rng1 As Range, Rng2 As Range) As String
    Getx = Join(Filter(Evaluate("=ÏF(" & Rng2.Address & "=""x""," & Rng1.Address & ",""V"")"), "V", False), ",")
    End Function
    

    0 讨论(0)
提交回复
热议问题