1
If Worksheets("Data").Range("D5").value = 0 Then
Columns("K").EntireColumn.Hidden = True
Else
Columns("K").EntireColumn.Hidden = False
End If

Sir, I have the above code where Column "K" is hide/unhide based on the cell "D5" of another sheet. But when I Add or Delete Column in my excel then my desired column no. shift to "L" or "J" but column "K" static in VBA and hide by this code which should not happen. How this column "K" automatically change when a column delete or add in excel

4

2 回答 2

2

如果您在搜索“Homeloan”一词之前取消隐藏所有列没有问题,即使您删除或添加列也应该有效。

Sub test()

Dim lcol As Long
With Worksheets("Data")
    .Columns("A:AC").EntireColumn.Hidden = False 'Unhide all the columns first

    'This only works if the column with the word homeloan is not hidden.
    lcol = Application.WorksheetFunction.Match("Homeloan", .Range(.Cells(1, 1), .Cells(1, .Cells(1, .Columns.Count).End(xlToLeft).Column)), 0) 'Find last column in row 1. Then create a range to look for the word "Homeloan". Last, return the current column number where Header "Homeloan" exists.
        If .Range("D5").Value = 0 Then
            .Columns(lcol).EntireColumn.Hidden = True
        Else
            .Columns(lcol).EntireColumn.Hidden = False
        End If
End With
End Sub
于 2018-10-30T12:13:51.800 回答
2

我建议您在要显示/隐藏的列的顶部单元格中输入一个名称(“命名范围”)。然后你可以在代码中访问这个命名的 Range。

假设您"Homeloan"在 Cell 上定义了名称K1:写

Range("HomeLoan").EntireColumn.Hidden = False

请注意,您应该始终限定 Excel 对象,以便清楚要访问哪个工作表,但这不是您的问题的一部分

于 2018-10-30T12:14:00.443 回答