使用VBA在Excel中search文本string

我试图在macros中使用VBAsearch文本string并删除列的内容。 我之前在网站上发现了这一点,并希望将其更改为search列,并在保留列的同时删除文本“QA1”。 我希望这是有道理的。

LastRow = Cells(Columns.Count, "D").End(xlUp).Row For i = LastRow To 1 Step -1 If Range("D" & i).Value = "D" Then Range("D" & i).EntireColumn.Delete End If Next i 

如果一个单元格包含QA1您希望清除整列的内容?

 Sub Test() Dim rCell As Range With ThisWorkbook.Worksheets("Sheet1").Columns(4) Set rCell = .Find("QA1", LookIn:=xlValues) If Not rCell Is Nothing Then .ClearContents End If End With End Sub 

如果您只想清除D列中的每个QA1实例:

 Sub Test() Dim rCell As Range With ThisWorkbook.Worksheets("Sheet1").Columns(4) Set rCell = .Find("QA1", LookIn:=xlValues) If Not rCell Is Nothing Then Do rCell.ClearContents Set rCell = .FindNext(rCell) Loop While Not rCell Is Nothing End If End With End Sub 

是否可以将其写入查看整个工作表并删除发现的QA1?

表单中的所有QA1实例:

 Sub Test() Dim rCell As Range With ThisWorkbook.Worksheets("Sheet1").Cells Set rCell = .Find("QA1", LookIn:=xlValues) If Not rCell Is Nothing Then Do rCell.ClearContents Set rCell = .FindNext(rCell) Loop While Not rCell Is Nothing End If End With End Sub 

编辑:添加LookAt:=xlWholeFind参数,所以它不会删除包含QA1和其他文本的单元格(例如QA11Some text QA1

此代码遍历指定行中的列,并删除“QA1”(如果find)

 Dim LastColumn As Integer Dim RowNumber As Integer Dim i As Integer LastColumn = UsedRange.SpecialCells(xlCellTypeLastCell).Column RowNumber = 1 'Adjust to your needs For i = 1 To LastColumn Step 1 Cells(RowNumber, i).Value = Replace(Cells(RowNumber, i).Value, "QA1", "") Next i 

循环使用活动工作表的使用范围,并删除选定的文本。

 Sub RemoveText() Dim c As Range Dim removeStr As String removeStr = InputBox("Please enter the text to remove") For Each c In ActiveSheet.UsedRange If c.Value = removeStr Then c.Delete Next c End Sub