2012-12-10 2 views
0

첫 번째 행에 특정 문자열이 포함 된 통합 문서가 있습니다. 예를 들어, A-D 행에서 "Dog", "Cat", "Squirrel"및 "Fish"가 있다고 가정 해 봅시다. 'Dog'및 'Squirrel'값을 검색하는 매크로를 원합니다. 열을 숨긴 다음 "Cat"및 "Fish"의 너비를 11로 설정합니다.첫 번째 행의 문자열을 기반으로 열을 숨기고 너비를 설정하려면 어떻게해야합니까?

모든 통합 문서에서 일관성이 없기 때문에 열 번호를 사용할 수 없습니다. 당신의 도움을 주셔서 감사합니다. 원하는 범위 이상의 동적 뭔가 : ("D1 A1") :

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

입니다 먼저 어떤 열이 작동해야하는지 식별해야합니다. 각 열을 살펴보고 특별히 이름이 지정된 변수에 열 번호를 저장하는 루프를 만드는 것이 좋습니다. 모든 열을 분류하면 숨기거나 크기를 조정할 수 있습니다. – PowerUser

답변

1

변경 범위 숨기고 열 크기를 조정하기 전에 여기

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 
+0

감사합니다. 별도로 열을 숨기는 하위 추가 "전역 개체 범 위"오류를 가져 오는 중입니다. 서브 클로우즈 Hide_Column() 범위 ("A, C : AV, AY : BA, BJ : BR") 선택 Selection.EntireColumn.Hidden = True End Sub – STANGMMX

+0

범위가 범위가 아닙니다. 사용 범위 ("AC : AV, AY : BA, BJ : BR"). – InContext

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 
관련 문제