我正在建立一个员工培训数据库,我希望能够在员工离开后删除其所有实例。他们的员工编号在F列中(因为许多员工使用相同的姓名,所以编号最简单)。
因此,我想搜索该员工编号的所有实例并删除整行。我能够使它删除雇员编号的一个实例,但随后找不到下一个。我添加了 SELECT mixed_id FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS row_num,
id,
idnew
FROM myTable
) AS x
UNPIVOT
(
mixed_id for item in (id, idnew)
) AS y
WHERE mixed_id IS NOT NULL
ORDER BY row_num, mixed_id;
命令,但收到错误消息:
无法获取
FindNext
类的FindNext
属性。
为什么Range
没问题,但Find
没问题?
代码如下:
FindNext
答案 0 :(得分:1)
与其循环遍历范围内的每个单元,不如使用Do...Loop While
循环并在findValue
为Nothing
时退出循环。
Dim rgF As Range
Set rgF = Sheet2.Columns("F")
Do
Set findValue = rgF.Find(what:=Reg4, LookIn:=xlValues, lookat:=xlWhole)
If Not findValue Is Nothing Then findValue.EntireRow.Delete
Loop While Not findValue Is Nothing
答案 1 :(得分:0)
一种更好的FIND()
方法是使用类似以下内容的方法:
Dim rgF As Range
Set rgF = Sheet2.Range("F:F")
For Each cll In rgF
Set c = .Find(Reg4, LookIn:=xlValues)
If c Is NOT Nothing Then
' Do whatever
Next
Next
答案 2 :(得分:0)
您的问题是由于您要删除 findvalue 而试图通过FindNext调用将其用作 After:= findvalue 参数的事实。包含 findvalue 的行被删除后,该行将不再可供参考。
您可以继续删除行,但是后续调用必须是Range.Find,而不是Range.FindNext。
Set findvalue = rgF.Find(What:=Reg4, LookIn:=xlValues, LookAt:=xlWhole)
'if the ID doesn't exist, get out of there
If findvalue Is Nothing Then
Debug.Print "No one has that ID anymore"
Exit Sub
End If
Do
'delete the row that has the ID
findvalue.EntireRow.Delete
Set findvalue = rgF.Find(What:=Reg4, LookIn:=xlValues, LookAt:=xlWhole)
Loop While Not findvalue Is Nothing
或者,将所有Find / FindNext范围收集到一个联合中,并在收集它们后立即将其全部删除。
Dim rgF As Range, allFound As Range, addr As String
Set rgF = Sheet2.Range("F:F")
Set findvalue = rgF.Find(What:=Reg4, LookIn:=xlValues, LookAt:=xlWhole)
If findvalue Is Nothing Then
'If the ID doesn't exist, get out of there
Debug.Print "No one has that ID anymore"
Exit Sub
Else
'there is at least one row to delete
'store original range address
addr = findvalue.Address(0, 0)
'seed the union oof ranges
Set allFound = findvalue
Do
'collect into Union
Set allFound = Union(findvalue, allFound)
'find the next instance
Set findvalue = rgF.FindNext(after:=findvalue)
Loop Until findvalue.Address(0, 0) = addr
'delete all row inthe union
allFound.EntireRow.Delete
End If