VBA hide column if

2019-07-25 10:29发布

I hope you can help me with this challenge that I have in Excel VBA. I'm not sure how to explain this, but I'll do my best.

I want to "hide" two columns if, the two columns contains the same text in both cell "D4" and cell "E4".

The text in the columns will not always be the same. Sometimes it's fx "TEST" in both of them "D4" & "E4", sometimes the text is "NOTEST" in both cells, and sometimes again it might only have the text in one out of the two cells, which means the column shouldn't be hidden.

If the explanation is to weak, please let me know and I'll try to explain it differently.

Thanks in advance!

2条回答
The star\"
2楼-- · 2019-07-25 10:40

You can use the following Sub.

Sub ShowColumns()
Dim firstCaseToCheck As String
Dim secondCaseToCheck As String
Dim nameOfYourSheet As String

firstCaseToCheck = "D4"
secondCaseToCheck = "E4"
nameOfYourSheet = "Name Of Your Sheet"

With ThisWorkbook.Sheets(nameOfYourSheet)
    If (.range(firstCaseToCheck) = .range(secondCaseToCheck)) Then
        .range(Split(Cells(1, .range(firstCaseToCheck).Column).Address(True, False), "$")(0) & ":" & _
                Split(Cells(1, .range(secondCaseToCheck).Column).Address(True, False), "$")(0)).EntireColumn.Hidden = True
    Else
        .range(Split(Cells(1, .range(firstCaseToCheck).Column).Address(True, False), "$")(0) & ":" & _
                Split(Cells(1, .range(secondCaseToCheck).Column).Address(True, False), "$")(0)).EntireColumn.Hidden = False
    End If
End With
End Sub

You can choose your two cells in firstCaseToCheck and secondCaseToCheck and choose your sheet with nameOfYourSheet. This will let you change all this without problem.

查看更多
何必那么认真
3楼-- · 2019-07-25 10:50

Give this a try:

Sub HiddenTreasure()
    If Range("D4") = Range("E4") Then
        Range("C:D").EntireColumn.Hidden = True
    Else
        Range("C:D").EntireColumn.Hidden = False
    End If
End Sub
查看更多
登录 后发表回答