2016-03-15 73 views
1

數據佈局:從A3開始到A(沒有特定的最後一行)在名稱管理器中稱爲= PeriodPrev。 = PeriodPrev是我用來標記數據的標籤。 = PeriodCurr標籤在PeriodPrev的最後一個已填充行之後開始。 PeriodPrev和PeriodCurr的其餘數據位於列E到W.根據單元格範圍清除行的內容

代碼:如何在列A和列E中爲屬於= PeriodPrev的數據創建列A和列E中的數據清除內容? 我試過下面的代碼,但它並沒有完全達到上述目的。 「如果c.Value = 」PeriodPrev「,然後」 返回錯誤13. 「如果c.Value =範圍(」 PeriodPrev 「)然後」 返回錯誤1004

Sub BYe() 
'The following code is attached to the "Clear" button which deletes Previous Period data 

    Dim c As Range 

    Dim LastRow As Long 

    Dim ws As Worksheet 


    ws = ThisWorkbook.Worksheets("Sheet1") 


    LastRow = Range("A" & Rows.count).End(xlUp).Row 

    For Each c In Range("A3:A" & LastRow) 
     If c.Value = "PeriodPrev" Then 
     ' If c.Value = Range("PeriodPrev") Then 
     c.EntireRow.ClearContents 
     End If 

    Next c 

End Sub 

回答

0

使用相交

If Not Application.Intersect(c, Range(yourLabel)) Is Nothing Then 

設我知道如果它不起作用

0

該代碼有一些錯誤。我試圖解決一些與註釋有關的問題

Sub BYe() 
    'The following code is attached to the "Clear" button which deletes Previous Period data 
    Dim c As Range, lastRow As Long, ws As Worksheet 

    'you need to SET a range or worksheet object 
    Set ws = ThisWorkbook.Worksheets("Sheet1") 

    'you've Set ws, might as well use it 
    With ws 
     lastRow = .Range("A" & Rows.Count).End(xlUp).Row 
     For Each c In .Range("A3:A" & lastRow) 
      'the Intersect determines if c is within PeriodPrev 
      If Not Intersect(c, .Range("PeriodPrev")) Is Nothing Then 
       'this clears columns A and E:W on the same row as c. 
       .Range(.Cells(c.Row, "A"), .Cells(c.Row, "E").Resize(1, 19)).ClearContents 
      End If 
     Next c 
    End With 
End Sub 

以下應該執行相同的操作而不使用循環。

Sub BYe2() 
    'The following code is attached to the "Clear" button which deletes Previous Period data 
    Dim lastRow As Long, ws As Worksheet 

    Set ws = ThisWorkbook.Worksheets("Sheet1") 

    With ws 
     lastRow = .Range("PeriodPrev").Rows(.Range("PeriodPrev").Rows.Count).Row 
     .Range("A3:A" & lastRow & ",E3:W" & lastRow).ClearContents 
    End With 
End Sub 
+0

我得到錯誤1004這一行: 「LASTROW = .Range(PeriodPrev).Rows(.Range(PeriodPrev).Rows.count).Row」 –

+0

我道歉。 PeriodPrev應該被引用。 – Jeeped

+0

嗨,Jeeped,它也行不通。我嘗試了下面的代碼,但在lastrow = ... etc這行仍然出現了相同的1004錯誤。 「子BYe2() 昏暗LASTROW只要 昏暗WS作爲工作表 昏暗RNG作爲範圍 集WS = ThisWorkbook.Worksheets( 「Data_LE」) 設置RNG = ThisWorkbook.Worksheets( 「宏」)。範圍(「PeriodPrev」) With ws lastRow = .Range(「PeriodPrev」).Rows(.Range(「PeriodPrev」).Rows.count).Row .Range(「A3:A」&lastRow&「, E3:W「&lastRow).ClearContents End With End Sub –

相關問題