选择具有相同ID号的所有行,然后迭代 - VBA

时间:2017-03-24 00:28:13

标签: excel vba

我在Excel中有一个ID的排序列表。我想抓住所有具有相同ID的行,然后我将操纵它们。

Sub Selectingabox()
Dim I As Integer
Dim N As Integer
'Defining
I = 1
N = 1
'Initializing
While I < 3000
'If I have more than 3k rows I'm in serious trouble anyways
If Range("A" & I).Select = Range("A" & I + 1).Select Then
 I = I + 1
Else: Range("A" & N, "AJ" & I).Select
'Lots of stuff manipulating the data range we just selected
N = I + 1
'The new top row
I = I + 1
'The new bottom row


Wend
End Sub

不太正常......对我不满意,我不知道为什么。也不知道代码是否有效!

2 个答案:

答案 0 :(得分:1)

在代码中添加End If - 这将解决编译错误

Sub Selectingabox()
Dim I As Integer
Dim N As Integer
'Defining
I = 1
N = 1
'Initializing
While I < 3000
'If I have more than 3k rows I'm in serious trouble anyways
If Range("A" & I).Select = Range("A" & I + 1).Select Then
 I = I + 1
Else: Range("A" & N, "AJ" & I).Select
'Lots of stuff manipulating the data range we just selected
N = I + 1
'The new top row
I = I + 1
'The new bottom row
End If ' add this here

Wend
End Sub

答案 1 :(得分:1)

一些事情:

  • 将您的值调整为长而不是整数,这样您就不会在第32k行收到错误
  • 使用FOR循环而不是while循环来提高代码效率
  • 而不是使用数字3000,您可以使用VBA使用Cells(Rows.Count, "A").End(xlUp).Row
  • 自动查找最后一行
  • 我不建议在代码中使用.Select。你想操纵什么?

    Sub Selectingabox()
    Dim I As Long
    Dim N As Long
    Dim lastrow As Long
    
    lastrow = Cells(Rows.Count, "A").End(xlUp).Row
    N = 1
    
    For I = 1 To lastrow
        If I = lastrow Then
            If Range("A" & I).Value <> Range("A" & I - 1).Value Then
            Range("A" & N & ":AJ" & I).Select
            N = I + 1
            End If
        Else
            If Range("A" & I).Value <> Range("A" & I + 1).Value Then
                Range("A" & N & ":AJ" & I).Select
            'Lots of stuff manipulating the data range we just selected
            N = I + 1
            End If
        End If
    Next I
    End Sub