需要使用VBA从Excel中的单词列表中删除特定的单词

我有列A中的单词列表(每行一个单词),我想删除某些单词并删除该特定的行。 我有下面的代码,但执行时不会执行任何操作(Nothing Happens)。 我无法弄清楚什么是错的。 请帮忙

Sub DeleteRowWithContents() Dim ExcludWords() As Variant Dim r As Long Dim txt As String Dim i As Long Dim LR As Long ExcludWords = Array("ANY", "I", "GO", "THROUGH", "OUT", "IT", "ALL", "TO", "THE", _ "BUT", "IN", "&", "E-MAIL", "AN", " FOR ", "US", "AS", "AND", _ "6-12CT", "WITH", "SAVINGS") Last = Range("A2").End(xlDown).Row For i = 1 To Last txt = Cells(i, "A") For r = 0 To UBound(ExcludWords) txt = Replace(txt, ExcludWords(r), "") Next r Next i End Sub 

我按照以下注释中的说明对代码进行了一些更改。

 Sub DeleteRowWithContents() Dim ExcludWords() As Variant Dim r As Long Dim txt As Range 'txt is a Range, so we can set it to a cell - you can't change the text of a cell by declaring that text as its own variable Dim ws As Worksheet 'specifically created a variable to refer to your spreadsheet, otherwise it always assumes the active sheet, which may not be appropriate Dim i As Long Dim LR As Long ExcludWords = Array("ANY", "I", "GO", "THROUGH", "OUT", "IT", "ALL", "TO", "THE", _ "BUT", "IN", "&", "E-MAIL", "AN", " FOR ", "US", "AS", "AND", _ "6-12CT", "WITH", "SAVINGS") Set ws = Sheets(1) 'set the ws variable to your current sheet (may need to change this depending on which sheet you run this on) LR = ws.Range("A" & ws.Rows.Count).End(xlUp).Row 'Note that I started from the bottom and went up, instead of starting from the top and going down. Less prone to error For i = 1 To LR 'Here you had referred to lastrow, which is not how you defined the variable above Set txt = ws.Cells(i, "A") ' For r = 0 To UBound(ExcludWords) txt.Formula = Replace(UCase(txt.Formula), ExcludWords(r), "") 'Note that I made the text in txt.Formula Uppercase as your ExcludWords is all uppercase Next r Next i End Sub 

我已经testing并确认,这在我的Sheet1上工作; 如果您不理解我上面的评论,请提问。 有些事情要根据我的变化来考虑:(1)提前为表单和单元格声明variables,这样以后可以更容易地使用它们; (2)确保你引用variables的方式与你声明的variables完全相同[在这里有助于描述性的名称,而不仅仅是“LR”或“txt”]。 最后(3)逐行testing你的代码,input代码编辑器并按f8,一次一行。 这将很清楚地显示你的错误。