简体   繁体   中英

using “Not equal” operator in Excel VBA

I'm currently working on a small macro that inserts a row if one of the following columns are a different number. I have the below peice of code but cannot understan why this isn't working.

Could anyone point out my mistake?

Sub Button1_Click()

Dim rowCount As Integer
rowCount = 10

If cell(rowCount, 2) <> cell((rowCount + 1), 2) Then
    Rows(rowCount).Insert
    rowCount = rowCount + 2
ElseIf cell(rowCount, 2) = cell((rowCount + 1), 2) Then
    rowCount = rowCount + 1

End Sub
  • cell is neither defined nor Set ... use Cells .
  • It's best to be explicit: add the .Value to indicate you are comparing values.
  • Use a simple Else instead of ElseIf... and include the End If .
If Cells(rowCount, 2).Value <> Cells((rowCount + 1), 2).Value Then
    Rows(rowCount).Insert
    rowCount = rowCount + 2
Else
    rowCount = rowCount + 1
End If

PS Do not use Integer for tracking rows, but use Long instead always . See this thread for the full detail.

PPS Always use Option Explicit , which would flag the undeclared variable cell .

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