我有一个Excel代码,可以删除所有我没有输入的内容。
如果用户输入狗,猫,房子,然后结束所有包含单词“狗,猫和房子”的单元格,则应保留。所有其他单元格都应删除。
现在,如果用户先写例如Dog然后再写END,它将起作用。然后它将删除所有单元格,但显示“狗”的位置。如果用户输入以下内容,则我需要它工作:狗,猫,房子然后结束
Sub test()
Dim objectsToRemove As New Collection '<-- collection to store all the strings
Dim currentObject As String
Do While currentObject <> "END" '<-- while the input is different than "END", we keep on asking inputs
currentObject = InputBox("which objects do you want to keep, ie some on the screen:")
If currentObject <> "END" Then objectsToRemove.Add currentObject '<-- and add them to the collection
Loop
Dim myrange As Range
Set myrange = ThisWorkbook.Worksheets("Tabell").UsedRange
For Each cell In myrange.Cells
For Each obj In objectsToRemove '<-- we apply the same logic of yours to each obj inside objectsToRemove
If Not (cell.Value Like obj & "*") Then
cell.Value = ""
End If
Next obj
Next
End Sub
答案 0 :(得分:2)
您需要将单元格清除代码放入循环之外。使用boolean
检查是否应清除单元格:
Dim someBool as Boolean ' Should be named something meaningful to you
' to understand the logic 6 months down the line
' Other code
For Each cell In myrange.Cells
someBool = True
For Each obj In objectsToRemove ' Should be named objectsToKeep
If (cell.Value Like "*" & obj & "*") Then
someBool = False
End If
Next obj
If someBool Then cell.Value = ""
Next