如何根据第一行中的字符串隐藏列并设置宽度?

时间:2012-12-10 16:57:36

标签: excel vba

我在第一行有一堆带有特定字符串的工作簿。所以,例如我,说我在A - D行中有“狗”,“猫”,“松鼠”和“鱼”。我想有一个宏来搜索'狗'和'松鼠'的值,并隐藏列,然后将“Cat”和“Fish”的宽度设置为值11.

我不能只使用列号,因为它们在我的所有工作簿中都不一致。谢谢你的帮助。

Sub HideColumn1()
If Range("B4").Value = 0 Then
    Columns("H").EntireColumn.Hidden = True
Else
    Columns("H").EntireColumn.Hidden = False
End If
End Sub

2 个答案:

答案 0 :(得分:1)

将范围(“A1:D1”)更改为您想要的范围或更具动态性的内容:

Dim cell As Range
Dim hiddenRng As Range, widthRng As Range

For Each cell In Range("A1:D1")

    If cell = "Dog" Or cell = "Squirrel" Then

        If (hiddenRng Is Nothing) Then
            Set hiddenRng = cell
        Else
            Set hiddenRng = Union(hiddenRng, cell)
        End If

    End If

    If cell = "Cat" Or cell = "Fish" Then

        If (widthRng Is Nothing) Then
            Set widthRng = cell
        Else
            Set widthRng = Union(widthRng, cell)
        End If

    End If

Next cell

If (Not hiddenRng Is Nothing) Then hiddenRng.EntireColumn.Hidden = True
If (Not widthRng Is Nothing) Then widthRng.EntireColumn.ColumnWidth = 11

答案 1 :(得分:0)

这是另一个例子

Sub hideColumns()
Dim iRow, iCol As Integer
iRow = 1
iCol = 1

Dim cat, dog, fish, squirrel As String

cat = "Cat"
dog = "Dog"
fish = "Fish"
squirrel = "Squirrel"

Do While Cells(iRow, iCol).Value <> ""
    If Cells(iRow, iCol).Value = dog Or Cells(iRow, iCol).Value = squirrel Then
        Cells(iRow, iCol).Select
        Selection.EntireColumn.Hidden = True
    ElseIf Cells(iRow, iCol).Value = cat Or Cells(iRow, iCol).Value = fish Then
        Cells(iRow, iCol).EntireColumn.Select
        Selection.ColumnWidth = 11
    Else
        'did not find anything do somthing
    End If

iCol = iCol + 1
Loop
End Sub