删除联合范围错误

我在rng_select.Delete行收到错误“Object or With Block Variable not set”。 我试过没有运气的Debug.Print.rng_select.address。 我的表被激活 – 有什么想法?

Sub Delete() Dim wkb As Workbook Dim Command As Worksheet, Data As Worksheet, Transfer AsWorksheet, Accredited As Worksheet, FollowUp As Worksheet Dim LcellData As Long, LcellTransfer As Long, LcellFollowUp As Long, LcellAccredited As Long, a As Long, b As Long Dim rng_select As Range Set wkb = Application.ActiveWorkbook Set Command = wkb.Sheets("Command") Set Data = wkb.Sheets("Data") Set Transfer = wkb.Sheets("Transfers") Set FollowUp = wkb.Sheets("FollowUp") Set Accredited = wkb.Sheets("Accredited") LcellFollowUp = FollowUp.Cells(Rows.Count, "A").End(xlUp).Row FollowUp.Activate For a = LcellFollowUp To 2 Step -1 If Cells(a, 8).Value = Cells(a - 1, 8).Value Then If rng_select Is Nothing Then Set rng_select = Cells(a, 1).EntireRow Else Set rng_select = Union(rng_select, Cells(a, 1).EntireRow) End If End If Next a rng_select.Delete Exit Sub 

我在rng_select.Delete行收到错误“Object or With Block Variable not set”

你正在得到那个错误,因为rng_select什么也没有。 这可能是因为代码永远不会进入For循环中的If/EndIF

要检查,请将此rng_select.Delete更改为

 If Not rng_select Is Nothing Then rng_select.Delete Else MsgBox "Range not valid" End If 

另外,请避免使用.Activate 。 你可能想看到这个

你的代码可以写成

 Sub Delete() Dim wkb As Workbook Dim Command As Worksheet, Data As Worksheet, Transfer As Worksheet Dim Accredited As Worksheet, FollowUp As Worksheet Dim LcellData As Long, LcellTransfer As Long, LcellFollowUp As Long Dim LcellAccredited As Long, a As Long, b As Long Dim rng_select As Range Set wkb = Application.ActiveWorkbook Set Command = wkb.Sheets("Command") Set Data = wkb.Sheets("Data") Set Transfer = wkb.Sheets("Transfers") Set FollowUp = wkb.Sheets("FollowUp") Set Accredited = wkb.Sheets("Accredited") With FollowUp LcellFollowUp = FollowUp.Range("A" & .Rows.Count).End(xlUp).Row For a = 2 to LcellFollowUp '<~~ No need for reverse loop If .Cells(a, 8).Value = .Cells(a - 1, 8).Value Then If rng_select Is Nothing Then Set rng_select = .Cells(a, 1).EntireRow Else Set rng_select = Union(rng_select, .Cells(a, 1).EntireRow) End If End If Next a End With If Not rng_select Is Nothing Then rng_select.Delete Else MsgBox "Range not valid. No Matching range found" End If End Sub