2017-05-19 177 views
1

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

例如 enter image description here

我走过很多问题上堆栈溢出过去了,我没有发现任何有用的。
感谢您的帮助!

+0

你尝试过什么?参加了VBA初学者指南? – Pierre

+0

不,我没有得到任何东西@Pierre –

回答

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

+0

得到一个错误,就像我在运行代码时一样,你能解释一下什么是WhereToPaste.Resize(UBound(b,1))。Value = Application.Transpose(b()) –

+0

更新了这篇文章。会尝试这个,因为我发送此推荐 –

+0

否它给出错误,如“无效的过程调用或参数” –