2017-01-02 119 views
0

如果日期是今天,我有這個代碼用於總結幾行。它工作正常,但我有幾個工作表,例如...表1,2,3,4,5。如果我在工作表1中輸入數據,然後運行此代碼它工作正常,但如果我在工作表1中輸入數據,然後跳過sheet2並轉到3,它將零表中的內容放在sheet2中。如果日期小於今天,我會在底部附近註釋掉退出子,但這樣做代碼會死掉。我怎樣才能使這個運行只有當前使用的工作表?我想忽略所有其他工作表。Excel VBA總結按行數

Sub Sum_TodaysDate() 

On Error Resume Next 

Dim sh As Worksheet 

For Each sh In ActiveWorkbook.Worksheets 

Dim LastRow As Long, iCount As Long 
Dim icell As Range 
Dim dSplit As Variant 
Dim dIndex As Date 

LastRow = sh.Range("D" & Rows.Count).End(xlUp).Row 
iCount = 0 

For Each icell In sh.Range("D2:D" & LastRow) 
    dSplit = Split(icell.Value, " ") 
    dIndex = Format(dSplit(0), "mm/dd/yyyy") 
    If dIndex = Date Then 
     iCount = iCount + 1 
     icell.Offset(0, 1).Value = "|" 
    End If 
Next icell 

'If sh.Range("E" & LastRow).Value < Date Then Exit Sub 
sh.Range("E" & LastRow).Value = iCount 
sh.Range("E" & LastRow).Font.Color = vbRed 


Next sh 

Application.ScreenUpdating = False 

End Sub 
+0

你知道代碼是如何工作的呢?如果它適用於所有工作表,那麼刪除循環應該非常簡單 – psubsee2003

回答

1

替換:

For Each sh In ActiveWorkbook.Worksheets 

有:

Set sh = ActiveSheet 

然後取出:

Next sh 
+0

謝謝!我不知道我在這裏出了什麼問題,我認爲不是SET SH,我只是徹底刪除它以擺脫for循環。 – Noob2Java