简体   繁体   中英

Excel VBA code to clear data from one cell based on another cell value

I'm self taught and having an issue with something I thought would be easy. I have a spreadsheet that i need to loop through column O and find any cell with data and clear contents of the corresponding cell in column H. The spread is sheet is ever changing so the last row of data is always changing. Below is the code I have been playing with but can't seem to get to work. Any help would be awesome..

    Dim deleterate As Long
    Dim ws As Worksheet

' set object
Set ws = Sheets("Import file")


' loop through the data to find the $$ amounts in column o

For deleterate = ws.Range("O" & Row.count).End(xlUp).Row To 1 Step -1

' indentify values in O which have value

If ws.Range("O" & deleterate).Value <> 0 Then
Cells(0, 7).ClearContents
End If

You can't have a row of 0 , so your line

Cells(0, 7).ClearContents

will give an error. You should also always qualify which sheet you are referring to, unless you know you want to use the ActiveSheet .


So you should use

ws.Cells(deleterate, 8).ClearContents

to specify the correct row and column (because "H" is the 8th column, not the 7th) or even

ws.Cells(deleterate, "H").ClearContents

or, to be consistent with your previous line (the If statement), you could use

ws.Range("H" & deleterate).ClearContents

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