2014-02-15 84 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,但根據我所見,做後者並沒有什麼壞處。