将所有单元格从一列向下移动一行(偏移量)

时间:2018-12-27 09:43:00

标签: excel vba

我想将一列中所有单元格(在我的情况下为C列)下移一行。这意味着如果我在单元格C1中写有“ X”,它应该向下移动到单元格C2,如果我在单元格C1000中写有“ Y”,它应该向下移动到单元格C1001…

我收到以下错误消息:

  

运行时错误1004,应用程序定义或对象定义的错误

Sub movedownrowcolumnC()    
    Range("C:C").Offset(1).Select
End Sub

4 个答案:

答案 0 :(得分:2)

使用:

Cells(Rows.Count, "C").End(xlUp).Offset(1).Select

尽管您很可能不需要Select,而只需使用Range变量:

Sub movedownrowcolumnC()
    Dim myRange As Range
    Set myRange = Cells(Rows.Count, "C").End(xlUp).Offset(1)

    myRange.Value = "myValue"
End Sub

要使Range对象明确引用其Worksheet引用,不仅要有“良好的编码习惯”,而且要:

Sub movedownrowcolumnC()
    Dim myRange As Range

    With Worksheets("mySheetName") ' reference wanted worksheet (change "mySheetName" to your actual relevantsheet name)
        Set myRange = .Cells(.Rows.Count, "C").End(xlUp).Offset(1) ' ser referenced worksheet column C cells right below last not empty one
    End With

    myRange.Value = "myValue"
End Sub

答案 1 :(得分:2)

尝试下面的宏。

Sub MoveDowncolumn()
Dim lastRow As Integer
With Worksheets("Sheet1")
lstrow = .Cells(Rows.Count, "C").End(xlUp).Row
For i = lstrow To 1 Step -1
.Cells(i + 1, "C").Value = .Cells(i, "C").Value
Next i
End With
End Sub

答案 2 :(得分:2)

您要这个吗?

Range("C1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

答案 3 :(得分:1)

您可以:

Option Explicit

Sub Test()

    With ThisWorkbook.Worksheets("Sheet1")
        If .Range("C1").Value = "Test" Then
           .Rows(.Range("C1").Row + 1).Select
        End If
    End With

End Sub