2014-02-15 83 views
-1

我的列'A'有日期。格式如下:20130101列值上的excel vba行删除

这将是2013年1月1日。如何编写一个宏脚本来删除具有星期六或星期日日期的所有行?

谢谢你的帮助。

我试过以下,但它不起作用。

'Piece together the date. 
    dt = Mid(.Cells(Cell, 1), 7, 2) & "/" & _ 
     Mid(.Cells(Cell, 1), 5, 2) & "/" & Left(.Cells(Cell, 1), 4) 

    'If the date is a Sat or Sun, delete the row. 
    If Weekday(dt) = 1 Or Weekday(dt) = 7 Then 
     .Rows(Cell).EntireRow.Delete 
+2

以什么方式“它不工作”? – pnuts

回答

1

日期改组后,月和日切换。例如,20130101正在翻译为2013年1月1日,但20130102正在翻译为年2月1,2013年

更改此:

dt = Mid(.Cells(Cell, 1), 7, 2) & "/" & _ 
    Mid(.Cells(Cell, 1), 5, 2) & "/" & Left(.Cells(Cell, 1), 4) 

这样:

dt = Mid(.Cells(Cell, 1), 5, 2) & "/" & _ 
    Mid(.Cells(Cell, 1), 7, 2) & "/" & Left(.Cells(Cell, 1), 4) 
+0

非常感谢 – user1681664

1

假设你日期格式为年月日,那么你可以做到以下几点:

Sub RemoveSatSun() 
    Dim dt As Date 
    ' Replace Sheet1 with your own 
    With Worksheets("Sheet1") 
     i = 1 
     Do Until .Cells(i, 1).Value = "" 
      dt = Mid(.Cells(i, 1), 7, 2) & "/" & _ 
       Mid(.Cells(i, 1), 5, 2) & "/" & _ 
       Left(.Cells(i, 1), 4) 

      If Weekday(dt) = 1 Or Weekday(dt) = 7 Then 
       .Rows(i).Delete 
       ' Because we have removed a row, decrement i to ensure we 
       ' don't miss a row since Excel VBA does not have a 
       ' loop continue statement 
       i = i - 1 
      End If 

      i = i + 1 
     Loop 
    End With 
End Sub 

请注意,我有i = i -1当我们删除一行时,如果我们不删除,我们将跳过一行,因为我们增加了i。从你发布的代码中,我认为这是你问题的原因。

如果日期格式不同,请按照ARICH的建议进行相应的调整。

此外,在这种情况下,您可以拨打.Rows(i).Delete而不是.Rows(i).EntireRow.Delete,但根据我所见,做后者并没有什么坏处。