2016-02-01 107 views
1

我正試圖編寫一些VBA代碼,如果隱藏了另一個特定行,將取消隱藏整行。該宏還根據特定列中的值隱藏了一系列行。這方面工作正常 - 我有可靠的代碼。我無法獲得我描述的第一個功能。應該很容易做,只是不知道語法。這個子程序應該在打開工作簿時執行。VBA - 基於另一行的隱藏/未隱藏狀態隱藏/取消隱藏行

Private Sub Workbook_Open() 
Application.ScreenUpdating = False 

Dim targ As Range 
Dim msg As Range 

targ = "DETAILS!B6" 
msg = "DETAILS!B42" 

msg.EntireRow.Hidden = True 


With Range("DETAILS!B6:B40") 
     .EntireRow.Hidden = False 

     For Each cell In Range("DETAILS!B6:B40") 
     Select Case cell.Value 

     Case Is = 0 
     cell.EntireRow.Hidden = True 

     End Select 
     Next cell 
End With 


If targ.EntireRow.Hidden = True Then 
    msg.EntireRow.Hidden = False 
End If 

Application.ScreenUpdating = True 
End Sub 
+0

你在哪裏放置了這段代碼?它應該位於Workbook Object(ThisWorkbook)的專用模塊中。這是你的問題是的,代碼的作品,它只是沒有公開發射? – BruceWayne

+1

是的,它是'ThisWorkbook'對象。當我打開工作簿時,出現以下錯誤:運行時錯誤91:對象變量或塊變量未設置。當我點擊「調試」時,突出顯示的行是'targ =「DETAILS!B6」'。也許這是我分配給'targ'變量的值 –

回答

1

雖然你可以這樣調用的對象範圍:Range("DETAILS!B6:B40")

在VBA最好是接受這樣稱呼它:Sheets("DETAILS").Range("B6:B40")

我修復了幾個語法錯誤:

Private Sub Workbook_Open() 
Application.ScreenUpdating = False 

Dim targ As Range 
Dim msg As Range 

Set targ = Sheets("DETAILS").Range("B6") 
Set msg = Sheets("DETAILS").Range("B42") 

msg.EntireRow.Hidden = True 


With Sheets("DETAILS").Range("B6:B40") 
     .EntireRow.Hidden = False 
End With 

For Each cell In Sheets("DETAILS").Range("B6:B40") 
    Select Case cell.Value 
     Case 0 
      cell.EntireRow.Hidden = True 
    End Select 
Next cell 



If targ.EntireRow.Hidden = True Then 
    msg.EntireRow.Hidden = False 
End If 

Application.ScreenUpdating = True 
End Sub 
2

您需要設置變量,像下面

Private Sub Workbook_Open() 
Application.ScreenUpdating = False 

Dim targ As Range 
Dim msg As Range 

Set targ = "DETAILS!B6" 
Set msg = "DETAILS!B42" 

msg.EntireRow.Hidden = True 


With Range("DETAILS!B6:B40") 
    .EntireRow.Hidden = False 

    For Each cell In Range("DETAILS!B6:B40") 
    Select Case cell.Value 

    Case Is = 0 
    cell.EntireRow.Hidden = True 

    End Select 
    Next cell 
End With 


If targ.EntireRow.Hidden = True Then 
    msg.EntireRow.Hidden = False 
End If 

Application.ScreenUpdating = True 
End Sub 
2

哦!只需在targmsg之前放Set,因爲它們是Range。聲明範圍時,必須有Set,即Set myRng = Range("A1:A10")

可能需要做Set targ = Range("Details!B6")如果只是Set Targ = "DetailsB6"不起作用。

關於第二個想法,我不認爲Set Targ = "Details!B6"將工作,如果你是Dim Targ as Range。你是一個範圍昏暗,但聲明它像一個字符串。您需要這是一個範圍,使用它像targ.EntireRow.Hidden