2012-08-05 103 views
2

我寫了一個VBA腳本,該腳本應該隱藏在其他工作表中引用空單元格的行。可以這麼說,表1包含單元格A1,它是空的。工作表2的單元格A1包含「Sheet1!A1」,但打印出0.我的腳本應該穿過所有行並隱藏包含空引用的腳本,但似乎沒有這樣做。 如果你能幫我弄清楚我的錯誤,那將會很棒。這裏是我的代碼到目前爲止:Excel/VBA:檢查單元格引用是否返回0

Sub Hide() 
Application.ScreenUpdating = False 
Dim i As Integer 
For i = 1 To 1000 
If IsEmpty(Cells(1, i)) Then 
Rows(i).EntireRow.Hidden = True 
End If 
Next i 
Range("A1").Select 
Application.ScreenUpdating = True 
End Sub 

我會很感激任何形式的幫助。

最好的問候,

亞歷

+0

+ 1後,這個問題問得好!讓我想一會兒:) – 2012-08-05 23:09:07

回答

0

在循環中使用Cells(1, i)意味着你沿着列1行,而不是倒在A列的行我會懷疑你的工作要Cells(i, 1)代替。

由於CellsRows的調用未被限定,它們將引用活動工作表。從您的描述中,並不是100%清楚兩者是否應該引用同一張表。很明顯,例如,Sheet2!A1不能爲空,因爲它包含一個涉及Sheet1!A1的公式。

因此,您可能需要檢查Sheet1上的空單元格,但實際上是隱藏了Sheet2上的行。這將改變Worksheets("Sheet1").Cells(i, 1)Worksheets("Sheet2").Rows(i)

如果事情比較複雜的電話,你需要兩個檢查空虛和隱藏Sheet2行,那麼你要麼需要隱藏與A列中零值的所有行(可能如果Sheet1上的任何行實際上包含零作爲值,則會出現問題)或更改Sheet2上的公式以明確處理Sheet1上的空單元格。

例如,在Sheet2!A1公式可以是:=IF(ISBLANK(Sheet1!A1),#N/A,Sheet1!A1)

在宏的支票將被:

If IsError(Cells(i, 1).Value) Then 
    If (Cells(i, 1).Value = CVErr(xlErrNA)) Then 
    Rows(i).EntireRow.Hidden = True 
    End If 
End If 

你可以只使用IsError檢查,但可能會隱藏與真正的錯誤源數據(例如除以零)

1

亞歷克斯這裏是一個稍微複雜的做法。但它的工作原理:)

注意:這隻適用於在同一工作簿或打開的工作簿中引用工作表的公式。

邏輯

  1. 該代碼識別其具有下式,然後通過它們循環的細胞
  2. 然後同時通過其具有下式的所有單元循環,它檢查該單元格的.Precedents 。這是最棘手的部分。沒有簡單的方法來獲取位於另一個工作表或工作簿上的.Dependents.Precedents。你可以稱之爲這個屬性的限制。所以我正在使用一個替代方案來獲取這些:)
  3. 一旦我得到該單元格的地址,我正在檢查它們是否爲空,然後根據條件,我隱藏了單元格。

CODE

Sub Sample() 
    Dim ws As Worksheet 
    Dim rng As Range, acell As Range, bcell As Range 

    '~~> This is the sheet which has the formula 
    Set ws = Sheets("Sheet1") 

    With ws 
     '~~> Get the address of all the cells which have formulas 
     Set rng = .Cells.SpecialCells(xlCellTypeFormulas) 

     '~~> Loop through the cells 
     For Each acell In rng 
      If acell.EntireRow.Hidden = False Then 
       If acell.Value = 0 Then 
        On Error Resume Next 
         '~~> Clear any precedents/dependent arrows if any 
         .ClearArrows 
         '~~> Show precedents 
         acell.ShowPrecedents 
         '~~> Navigate to the relevant cell in the other worksheet 
         acell.NavigateArrow True, 1 
         '~~> Compare address and name to check if they are not from ws 
         If ActiveCell.Address <> rng.Address Or ActiveCell.Worksheet.Name <> .Name Then 
          Set bcell = Sheets(ActiveCell.Worksheet.Name).Range(ActiveCell.Address) 
          '~~> Check if it not empty 
          If Len(Trim(bcell.Value)) = 0 Then 
           '~~> If empty, hide the row 
           .Rows(acell.Row).EntireRow.Hidden = True 
          End If 
         End If 
         '~~> Clear any precedents/dependent arrows if any 
         .ClearArrows 
         .Activate 
        On Error GoTo 0 
       End If 
      End If 
     Next 
    End With 
End Sub 

快照

表1運行前宏

enter image description here

這是表2的外觀

enter image description here

而且這是工作表Sheet1的外觀宏

enter image description here

相關問題