如果标题下方没有数据删除标题

时间:2017-09-26 23:23:35

标签: excel vba excel-vba

所以我有一个削减和复制"打开订单"并在数据(See previous post)下面插入这些行,然后在开放订单数据上方标出一个标题。当前写入宏的方式,如果没有打开的订单数据,它会将标题一直向下延伸到第65k行。

见下面的代码:

Dim LastRow, NewLast, MovedCount As Integer
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row 'Find last Row
NewLast = LastRow + 1 'NewLast tracks the new last row as rows are copied and pasted at the end
    MovedCount = 0
 For I = 2 To LastRow
    If Left(Cells(I, 4), 1) = "O" Then    'Copy the row, increment NewLast and paste at the bottom.
        Rows(I).Cut
        'LastRow = LastRow - 1
        Cells(NewLast + 3, 1).Select
        ActiveSheet.Paste
        Rows(I).Delete
        I = I - 1  'Since we deleted the row, we must decrement i
        MovedCount = MovedCount + 1  'Keeps track of number of rows moved so as not to overshoot the original last line

      End If
    If I + MovedCount = LastRow Then Exit For 'Exit For loop if we reached the original last line of the file
Next I

'inserts a header for the open section
Cells(1, 1).Select
Selection.End(xlDown).Select
nRowMax = Selection.Row
Selection.Offset(1, 0).Select
Selection.EntireRow.Copy
Selection.End(xlDown).Select
Selection.Offset(-1, 0).Select
Selection.PasteSpecial xlPasteFormats
ActiveCell.Select
ActiveCell = "Open Orders"
Application.CutCopyMode = False

所以我的问题是,如果没有打开的订单数据,我怎么能保持标题不被复制?如果周围没有数据,我怎么能删除标题。

我正在考虑将一个IF放在标题THAN删除标题下面没有数据。对不起,如果这有点开放,我认为有几种方法可以解决这个问题。

请参阅下面的图片,了解使用和不使用未结订单时数据的外观。enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,那么如果没有未结订单,您根本不希望填写“未结订单”标题。您可以通过将代码的整个底部部分嵌套在if语句中来实现此目的:

If MovedCount <> 0 Then
  Cells(1, 1).Select
  ...
  Application.CutCopyMode = False
End If