我正在尝试创建一个会查看列的宏,如果它看到值更改,那么它会插入一个新行。我已经在下面编写了一些代码,但我正在获取应用程序定义或对象定义的错误。
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
任何帮助将不胜感激。
答案 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