Excel VBA脚本将两个单元格内容连接成一个

时间:2013-02-15 02:21:16

标签: excel-vba vba excel

Sub Concat()

   Do While ActiveCell <> "" 

      'The rows are filtered to display only "London"
      'The changes required are for "London" only

      If ActiveCell.Offset(0,0) = "London" Then
        ActiveCell.Offset(0, 0).FormulaR1C1 = _
           ActiveCell.Offset(0, 0) & " " & ActiveCell.Offset(0, 1)

        ActiveCell.Offset(0, 1) = ""
      End If
      ActiveCell.Offset(1, 0).Select
   Loop

End Sub

我有接近13500行。 这不起作用。我看不出任何明显的变化。

2 个答案:

答案 0 :(得分:1)

Sub Concat()

   Do While ActiveCell <> "" 

      With ActiveCell
         If .Value = "London" Then
             .Value = .Value & .Offset(0, 1).Value
             .Offset(0, 1).Value = ""
         End If
      End With

      ActiveCell.Offset(1, 0).Select

    Loop

End Sub

答案 1 :(得分:0)

您可以使用for each语句编写一个循环来循环遍历工作表的UsedRange中的所有行。对于每一行,检查行的第一列中的值是否为“London”,如果是,则使用column1&amp;的组合覆盖列的内容。列2。

然后只需将column3中的值复制到column2中,并使用ClearContents清除column3的值:

Sub Concat()

    'Loop through all the rows
    For Each Row In ActiveSheet.UsedRange.Rows

    'Look at the cell in the first column of the current row
    'If value is "London" concatinate column 1 and 2 and store in column1
    'Note, the check for "London" is an exact, case sensative check!

        If Row.Columns(1) = "London" Then
            Row.Columns(1) = Row.Columns(1) & " " & Row.Columns(2)
            Row.Columns(2) = Row.Columns(3)
            Row.Columns(3).ClearContents
        End If
    Next Row
End Sub