如何将合并单元格的值复制到其相邻单元格?

时间:2015-01-28 05:31:23

标签: excel vba excel-vba

我需要在活动工作表中找到合并的单元格并将值复制到相邻的单元格。
我尝试在下面写一个宏,但这不是复制单元格值。我在行Error 424

中收到ActiveSheet.Cells(row, col).Select

以下是我的表格:

    A       B
 **Merged Cell1**   
 Value1         
 Value2         
 Value3         
 text4          
 text5          
 text6          
 text7          
 text8          
 **Merged Cell3**           
 Value1         
 Value2         
 **Merged Cell4**           
 text4          
 text5          
 text6          
 text1          
 **Merged Cell5**           
 text4          
 text5          
 **Merged Cell5**           
 text           

Sub TestMacro5()
    Dim rcount As Integer
    Dim row As Integer
    Dim col As Integer
    Dim i As Integer

    ActiveSheet.Select
    col = 1
    row = 1
    i = 1
    rcount = Application.CountA(Range("A:A"))

    For i = 1 To rcount
        ActiveSheet.Cells(row, col).Select
        If Selection.MergeCells Then
            ActiveCell.Offset(1, 5).Value = ActiveCell.Value
            row = row + 1
            Exit Sub
        End If
    Next i
End Sub

1 个答案:

答案 0 :(得分:0)

最好不要使用.Select来确定您要处理的单元格或工作表。

Dim rcount As Long
Dim rw As Long
Dim cl As Long
With ActiveSheet
    cl = 1
    rw = 1
    rcount = .Cells(Rows.Count, 1).End(xlUp).row
    For rw = 1 To rcount
        If .Cells(rw, cl).MergeCells Then
            .Cells(rw, cl).Offset(1, 5) = .Cells(rw, cl).Value  '1 row down and 5 columns over ?
            Exit For   'why exit here?
        End If
    Next rw
End With

有关直接处理细胞,细胞范围和工作表的更多方法,请参阅How to avoid using Select in Excel VBA macros