简体   繁体   中英

Delete EntireRow that has a specific cell value

I'm trying to use this VBS code to delete an entire row that has a specific cell value, but it gives an error when I try to find the value and select the row:

Set xc = CreateObject("Excel.Application")
xc.Visible = false
xc.displayalerts=false
Set xp = xc.WorkBooks.Open ("C:\Users\Shahim\Desktop\test.xlsx")
Set xs = xp.Worksheets(1)

Set xc = xs.find(what:="Vtest",lookat:=xlwhole).select

Set xr = xc.ActiveCell.EntireRow.Select

xr.selection.delete
xp.save
xp.close()

You've got a number of issues:

  1. You need parentheses around function calls returning a value:

     set xp=xc.WorkBooks.Open("C:\\Users\\Shahim\\Desktop\\test.xlsx") 
  2. Find() operates on a range, not a sheet ( xs.find(...) is invalid).

  3. You can't use named parameters in VBScript ( what:="Vtest" is invalid).

  4. You need to define all Excel constants you're using:

     Const xlWhole = 1 

Taking all of that into consideration, try the following:

' Define constants...
Const xlWhole = 1

Set xc = CreateObject("Excel.Application")
xc.Visible = false
xc.displayalerts=false

' Use parens when calling functions...
set xp = xc.WorkBooks.Open("C:\Users\Shahim\Desktop\test.xlsx")

set xs = xp.Worksheets(1)

' Use Find() with a range (column A here, change as needed).
' Specify params by position, not name.
set xc = xs.Range("A:A").find("Vtest", , , xlwhole)

If Not xc Is Nothing Then
    xc.EntireRow.Delete
End If

xp.save
xp.close()

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