Excel的VBA宏连接

时间:2017-05-19 05:37:27

标签: excel-vba excel-2010 vba excel

我有一个要求,就像我在A列中有一些值,我在B,C,D列中有多个值。如果我的列包含值X,那么我想要将列标题和列A值连接起来。

例如 enter image description here

我在Stack Overflow上经历了很多问题,但我没有发现任何有用的东西 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

请尝试此代码。

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

应该像

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

输出就像

sample output

相关问题