VBA - 根据另一行

时间:2016-02-01 19:02:01

标签: excel vba excel-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

3 个答案:

答案 0 :(得分:2)

您需要设置如下所示的变量

#909

答案 1 :(得分:2)

哦!只需将Set放在targmsg之前,因为它们是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一样使用它

答案 2 :(得分: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