使用VBA,我如何将行放在"活动行"在一张桌子里

时间:2016-01-16 05:11:03

标签: excel-vba vba excel

当我在表格中插入一行时,它会在当前行上方插入一行,这很好。但后来我需要能够将那行插入活动行。我该怎么办?我的代码结构是:

For each row in [Table]
  If [condition] Then
    row.Insert 'this inserts a row above the "current" row
    'here I want to move to the row I just inserted
    ActiveSheet.Cells(row.row, [Table[Col]].Column) = 5 'arbitrary value
  End If
Next row

2 个答案:

答案 0 :(得分:1)

尝试OFFSET(row_no,col_no)

'To go to previous row use this
ActiveCell.Offset(-1, 0).Activate
'To got to next row use this
ActiveCell.Offset(1, 0).Activate

您也可以尝试以下代码:)

Sub test()
a = ActiveCell.Row - 1
Rows(a).Activate
End Sub

包含您的代码

For Each Row In [Table]
  If [Condition] Then
    Row.Insert 'this inserts a row above the "current" row
    'here I want to move to the row I just inserted
    a = ActiveCell.Row - 1
    Rows(a).Activate
  End If
Next Row

答案 1 :(得分:0)

似乎没有真正的方法可以做到这一点......所以我使用了一种解决方法。我在do while循环周围放了一个for循环,循环直到你到达表的最后一行。然后在for循环中,我让它在每行插入/删除后退出循环,并添加了一个处理空白(插入)行的elseif

Dim ExitLoop As Boolean: ExitLoop = False

Do While ExitLoop = False
    For Each row In [BacklogProjections].Rows
        If (some condition) Then
            row.Delete
            Exit For
        ElseIf (blank row) Then
            'copy appropriate data here
        ElseIf (other condition) Then
            row.Insert
            Exit For
        End If
        'backlogLastRow was initialized somewhere else in my code
        If row.row = backlogLastRow Then ExitLoop = True
    Next row
Loop