VBA Macro Concatenation for Excel

柔情痞子 提交于 2020-01-24 20:48:29

问题


I have a requirement like I have some values in column A and I have multiple values in column B,C,D. If my column contains value X then I want to column header and column A value to be concatenate.

For example

I have gone through lots of question on Stack Overflow and I didn't found anything helpful.
Thanks for your help!


回答1:


please try this code.

Sub FindValues(ByVal WhereToFind As Range, ByVal WhereToPaste As Range)
    'where to find should have the header and values
    Dim col As Integer  'loop through columns
    Dim row As Integer  'loop through rows
    Dim a() As Variant
    Dim b() As Variant
    Dim i As Integer

    a() = WhereToFind

    For row = 2 To UBound(a, 1)
    For col = 2 To UBound(a, 2)
        If a(row, col) = "x" Then
          i = i + 1
          ReDim Preserve b(1 To i)
          b(i) = a(1, col) & "=" & a(row, 1)
        End If
      Next
    Next
    WhereToPaste.Resize(UBound(b)).Value = Application.Transpose(b())
End Sub

that should be called like

Sub caller()
FindValues ThisWorkbook.Sheets("Sheet1").Range("A1:E4"), ThisWorkbook.Sheets("Sheet1").Range("F1")
End Sub

the output is like



来源:https://stackoverflow.com/questions/44062182/vba-macro-concatenation-for-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!