为什么使用variables删除listrows不起作用?
我想知道为什么我的代码不工作,当我使用一个variables从表中删除给定的行时,如果我工作正常,如果我把数字放在括号。 代码没有做任何特别的事情。 它经历一个循环,find我想要删除的行,然后返回它的编号。
并有我有问题的行: Inventory.ListRows(Talalat).Delete
'其中库存是Listobject和Talalat是长
我肯定从我想要删除的行的代码中得到正确的数字,它运行正常,没有错误消息,但它只是没有做什么。 但是,当我手动插入数字代码它工作得很好…任何想法?
PS:如果您想查看整个代码,请参阅下面的代码。
Private Sub CommandButton17_Click() Dim CounterA As Long Dim Talalat As Long Dim ANsWR As Integer Set invent = Sheets("CORE").ListObjects("Inventory") If Not ComboBox4.Value = "" And Not ComboBox4.Value = "<Új tárgy>" Then Talalat = 0 For CounterA = 1 To invent.Range.Rows.Count If ComboBox4.Value = invent.Range.Cells(CounterA, 1) Then Talalat = CounterA Next If Talalat > 0 Then ANsWR = MsgBox("Biztosan törli a(z) " & invent.Range.Cells(Talalat, 1) & Chr(13) & "nevű tárgyat az adatbázisból?", vbYesNo, "Tuti?") If ANsWR = vbNo Then Exit Sub Else Sheets("CORE").Unprotect invent.ListRows(Talalat).Delete 'Where the glitch is End If End If End If End Sub
您是否确定您正在为要删除的行获取正确的编号? 尝试添加“-1”之后:
If ComboBox4.Value = invent.Range.Cells(CounterA, 1) Then Talalat = CounterA
你的桌子上有一个标题吗? 假设答案是“是”,下面说明了为什么你应该使用.DataBodyRange
而不是.Range
。
这里有一些testing代码,类似于你的…
Sub myTest() Dim iLoop As Long Dim theRow As Long Dim userAns As Integer Dim myList As ListObject Set myList = Sheets("Sheet5").ListObjects("Table1") theRow = 0 For iLoop = 1 To myList.Range.Rows.Count If IsDate(myList.Range.Cells(iLoop, 1)) And myList.Range.Cells(iLoop, 1) > Now() Then theRow = iLoop Exit For End If Next iLoop If theRow > 0 Then userAns = MsgBox("Found " & myList.Range.Cells(theRow, 1) & " on Row " & theRow & ". Should I delete?", vbYesNo) If userAns = vbNo Then Exit Sub Else myList.ListRows(theRow).Delete End If End If End Sub
针对下面的表运行此代码,并显示标题,以提供正确的编号。 列A中比NOW更大的第一个date在第18行中。
但是,在对话框中select“是”时,我们看到它实际上删除了第19行。
下面的代码是相同的,但myList.Range
所有实例已经更改为myList.DataBodyRange
。 此外, IsDate(myList.DataBodyRange.Cells(iLoop, 1))
被删除,因为循环将不再检查标题…
Sub myTest() Dim iLoop As Long Dim theRow As Long Dim userAns As Integer Dim myList As ListObject Set myList = Sheets("Sheet5").ListObjects("Table1") theRow = 0 For iLoop = 1 To myList.DataBodyRange.Rows.Count If IsDate(myList.DataBodyRange.Cells(iLoop, 1)) And myList.DataBodyRange.Cells(iLoop, 1) > Now() Then theRow = iLoop Exit For End If Next iLoop If theRow > 0 Then userAns = MsgBox("Found " & myList.DataBodyRange.Cells(theRow, 1) & " on Row " & theRow & ". Should I delete?", vbYesNo) If userAns = vbNo Then Exit Sub Else myList.ListRows(theRow).Delete End If End If End Sub
当它用于同一个表时,它说NOW之后的第一个数据在第17行上。这是数据的第17行,不包括头。
当您单击是,然后正确的行被删除…
当在ListObject上定义了一个AutoFilter时,我们鼓励删除ListRows的问题。 我们能够通过在删除行之前删除filter来解决这个问题:
myList.AutoFilter.ShowAllData myList.ListRows(theRow).Delete