将两个不同的列与分隔符组合在一起

时间:2013-09-30 14:26:31

标签: excel vba

如何使用vba excel将两个不同的数据列合并为一列,例如ColumnA和ColumnC中的数据合并到ColumnF中,并使用逗号分隔符。如果我有一个输入框来选择要组合的列以及组合结果将出现在哪一列,那将是很好的。

例如:

 ColA    ColC    ColF
 Apple   Orang   Apple,Orang
 Pear    Grape   Pear,Grape

1 个答案:

答案 0 :(得分:2)

如果您真的想要一个宏来提示您输入不同的列,请尝试以下方法:

Sub Macro1()
  Dim firstCol As String
  firstCol = InputBox(Prompt:="Enter first column: ", Title:="Enter data", Default:="A")

  Dim secondCol As String
  secondCol = InputBox(Prompt:="Enter second column: ", Title:="Enter data", Default:="B")

  Dim resultCol As String
  resultCol = InputBox(Prompt:="Enter results column: ", Title:="Enter data", Default:="C")

  LastRow = Cells(Rows.Count, firstCol).End(xlUp).Row

  Dim comma As String
  comma = ","","","

  For Each rng In Range(firstCol & "1:" & firstCol & LastRow)
    Range(resultCol & rng.Row).Formula = "=CONCATENATE(" & firstCol & rng.Row & comma & secondCol & rng.Row & ")"
  Next
End Sub