我对vba相当新,只是卡住了。我有一个包含A1到BW50信息的电子表格。 Cell AM7包含某些值=(比方说)" Mytext"。我想编写一个代码来查找值并清除包含此特定文本的列之后的所有列。我知道我可以修理"列和清除它们,但这些列可能会改变" Mytext"之后,我希望一切都清除。我无法解决任何问题。有什么想法吗?
谢谢
答案 0 :(得分:0)
使用find方法可能是最快的:
Option Explicit
Sub Clear()
Dim rng As Range
Dim str As String
str = "text"
Set rng = ActiveSheet.Cells.Find(What:=str, After:=ActiveCell, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rng Is Nothing Then
Range(Columns(rng.Offset(0, 1).Column), Columns(rng.Offset(0, 1).Column).End(xlToRight)).Delete
Else
MsgBox "The value '" & str & "' was not found."
End If
End Sub
注意: LookAt:=xlWhole
如果您要查找文本的任何部分而不是整个单元格值,则应更改为LookAt:=xlPart
。
答案 1 :(得分:0)
你可以试试这个:
Option Explicit
Sub ClearColumns()
Dim f As Range
Dim textToFind As String: textToFind = "Mytext"
With Worksheets("mySheet").Range("A1:BW50") '<--| change "mySheet" with your actual sheet name
Set f = .SpecialCells(XlCellType.xlCellTypeConstants, xlTextValues).Find(What:=textToFind, LookAt:=xlWhole, LookIn:=xlValues, MatchCase:=False) '<--| look for text in given range cells withtext values
If Not f Is Nothing Then .Range(f.Offset(, 1), .Columns(.Columns.Count)).Resize(.Rows.Count).ClearContents '<--| if text found then clear given range columns at the right of the found text
End With
End Sub