用于检查列中的值何时更改的代码

时间:2018-03-05 09:46:00

标签: excel vba excel-vba

我正在尝试创建一个会查看列的宏,如果它看到值更改,那么它会插入一个新行。我已经在下面编写了一些代码,但我正在获取应用程序定义或对象定义的错误。

Sub FormatMyData()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Dim Value As String

    Value = Worksheets("Sheet1").Cells(2, D).Value
    Col = "D"
    StartRow = 1
    BlankRows = 1


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

    With Worksheets("Sheet1")
        For R = LastRow To StartRow + 1 Step -1
            If Worksheets("Sheet1").Cells(R, Col) <> Value Then
                Worksheets("Sheet1").Cells(R + 1, Col).EntireRow.Insert Shift:=xlDown
                 Value = Cells(R + 2, Col)
        End If

        Next R
    End With


End Sub

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您还应该说明错误发生在哪里,因此我们可以更轻松地为您提供帮助。

我找到的东西如下:

  • 使用Sheets代替Worksheets
  • 在您宣读Value使用.Cells(2,“D”)的行中。值
  • 在您的循环中更改Value您正在使用单元格而未指定Sheet
  • 因为您在工作表上使用了With,所以可以节省一些代码

所以改变你的代码:

Sub FormatMyData()

    Dim Col As Variant
    Dim BlankRows As Long
    Dim LastRow As Long
    Dim R As Long
    Dim StartRow As Long
    Dim Value As String

    Value = Sheets("Sheet1").Cells(2, "D").Value
    Col = "D"
    StartRow = 1
    BlankRows = 1


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

    With Sheets("Sheet1")
        For R = LastRow To StartRow + 1 Step -1
            If .Cells(R, Col) <> Value Then
                .Cells(R + 1, Col).EntireRow.Insert Shift:=xlDown
                 Value = .Cells(R + 2, Col)
            End If

        Next R
    End With


End Sub