简体   繁体   中英

Need to remove specific words from a List of words in excel using VBA

I have a list of words in Column A (one word per row), I want to remove certain words and delete that particular row. I have the below code but it doesn't do anything when executed(Nothing Happens). I cannot figure out what is wrong. Please help

  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

I made some changes to your code as noted in the comments below.

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

I have tested and confirmed that this works on my Sheet1; please ask questions if you don't understand my comments above. Some things to consider based on my changes: (1) Declare your variables for sheets and cells ahead of time, it makes it easier to work with them later; (2) Make sure you refer to variables exactly the same way as you declared them [it helps here to make very descriptive names, instead of just "LR" or "txt"]; and finally (3) test your code line by line by entering the code editor and pressing f8, one line at a time. This will reveal quite clearly where your errors are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM