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

时间:2015-08-12 14:28:12

标签: excel vba excel-vba

我在 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

1 个答案:

答案 0 :(得分:2)

我对您的代码进行了一些更改,如下面的评论中所述。

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

我已经测试并确认这适用于我的Sheet1;如果您不理解我的上述评论,请提出问题。根据我的更改要考虑的一些事项:(1)提前为工作表和单元格声明变量,以便以后更容易使用它们; (2)确保你引用的变量与你声明它们的方式完全相同[这有助于制作非常具有描述性的名称,而不仅仅是“LR”或“txt”];最后(3)通过输入代码编辑器并按f8,一次一行,逐行测试代码。这将很清楚地揭示您的错误。