메인 컨텐츠로 가기

Excel에서 병합 된 셀의 행 높이를 자동으로 맞추는 방법은 무엇입니까?

Excel에서는 다음을 사용하여 셀 내용에 맞게 행 높이를 빠르게 조정할 수 있습니다. 행 높이 자동 맞춤 그러나이 기능은 병합 된 셀을 완전히 무시합니다. 즉, 당신은 적용 할 수 없습니다 행 높이 자동 맞춤 병합 된 셀의 행 높이 크기를 조정하려면 병합 된 셀의 행 높이를 하나씩 수동으로 조정해야합니다. 이 기사에서는이 문제를 해결하는 몇 가지 빠른 방법을 소개 할 수 있습니다.

VBA 코드로 병합 된 셀의 행 높이 자동 맞춤


화살표 블루 오른쪽 거품 VBA 코드로 병합 된 셀의 행 높이 자동 맞춤

다음 스크린 샷과 같이 병합 된 셀이있는 워크 시트가 있고 전체 내용을 표시하기 위해 셀 행 높이의 크기를 조정해야한다고 가정하면 아래 VBA 코드가 여러 병합 된 셀의 행 높이를 자동으로 맞추는 데 도움이 될 수 있습니다. 다음과 같이 :

doc-autofit-merge-cells-1

1. 누르고 ALT + F11 키가 열립니다. Microsoft Visual Basic for Applications 창.

2. 딸깍 하는 소리 끼워 넣다 > 모듈을 클릭하고 다음 코드를 모듈 창.

VBA 코드 : 여러 병합 된 셀의 행 높이 자동 맞춤
Option Explicit
Public Sub AutoFitAll()
  Call AutoFitMergedCells(Range("a1:b2"))
   Call AutoFitMergedCells(Range("c4:d6"))
    Call AutoFitMergedCells(Range("e1:e3"))
End Sub
Public Sub AutoFitMergedCells(oRange As Range)
  Dim tHeight As Integer
  Dim iPtr As Integer
  Dim oldWidth As Single
  Dim oldZZWidth As Single
  Dim newWidth As Single
  Dim newHeight As Single
  With Sheets("Sheet4")
    oldWidth = 0
    For iPtr = 1 To oRange.Columns.Count
      oldWidth = oldWidth + .Cells(1, oRange.Column + iPtr - 1).ColumnWidth
    Next iPtr
    oldWidth = .Cells(1, oRange.Column).ColumnWidth + .Cells(1, oRange.Column + 1).ColumnWidth
    oRange.MergeCells = False
    newWidth = Len(.Cells(oRange.Row, oRange.Column).Value)
    oldZZWidth = .Range("ZZ1").ColumnWidth
    .Range("ZZ1") = Left(.Cells(oRange.Row, oRange.Column).Value, newWidth)
    .Range("ZZ1").WrapText = True
    .Columns("ZZ").ColumnWidth = oldWidth
    .Rows("1").EntireRow.AutoFit
    newHeight = .Rows("1").RowHeight / oRange.Rows.Count
    .Rows(CStr(oRange.Row) & ":" & CStr(oRange.Row + oRange.Rows.Count - 1)).RowHeight = newHeight
    oRange.MergeCells = True
    oRange.WrapText = True
    .Range("ZZ1").ClearContents
    .Range("ZZ1").ColumnWidth = oldZZWidth
  End With
End Sub

배송 시 요청 사항:

(1.) 위의 코드에서 새 범위를 추가 할 수 있습니다. AutoFitMergedCells (Range ( "a1 : b2")) 호출 원하는대로 여러 번 스크립트를 작성하고 병합 된 셀 범위를 필요에 맞게 변경합니다.

(2.) 현재 워크 시트 이름을 변경해야합니다. Sheet4 사용한 시트 이름에.

3. 그런 다음 F5 키를 눌러이 코드를 실행하면 병합 된 모든 셀이 셀 내용에 자동으로 맞춰진 것을 볼 수 있습니다. 스크린 샷을 참조하십시오.

doc-autofit-merge-cells-1


관련 기사 :

Excel에서 열 너비를 자동으로 맞추는 방법은 무엇입니까?

최고의 사무 생산성 도구

🤖 Kutools AI 보좌관: 다음을 기반으로 데이터 분석을 혁신합니다. 지능형 실행   |  코드 생성  |  사용자 정의 수식 만들기  |  데이터 분석 및 차트 생성  |  Kutools 기능 호출...
인기 기능: 중복 항목 찾기, 강조 표시 또는 식별   |  빈 행 삭제   |  데이터 손실 없이 열이나 셀 결합   |   수식없이 반올림 ...
슈퍼 조회: 다중 기준 VLookup    다중 값 VLookup  |   여러 시트에 걸친 VLookup   |   퍼지 조회 ....
고급 드롭다운 목록: 드롭다운 목록을 빠르게 생성   |  종속 드롭다운 목록   |  다중 선택 드롭 다운 목록 ....
열 관리자: 특정 개수의 열 추가  |  열 이동  |  Toggle 숨겨진 열의 가시성 상태  |  범위 및 열 비교 ...
특색 지어진 특징: 그리드 포커스   |  디자인보기   |   큰 수식 바    통합 문서 및 시트 관리자   |  리소스 라이브러리 (자동 텍스트)   |  날짜 선택기   |  워크 시트 결합   |  셀 암호화/해독    목록으로 이메일 보내기   |  슈퍼 필터   |   특수 필터 (굵게/기울임꼴/취소선 필터링...) ...
상위 15개 도구 세트12 본문 도구 (텍스트 추가, 문자 제거,...)   |   50+ 거래차트 유형 (Gantt 차트,...)   |   40+ 실용 방식 (생일을 기준으로 나이 계산,...)   |   19 삽입 도구 (QR 코드 삽입, 경로에서 그림 삽입,...)   |   12 매출 상승 도구 (숫자를 단어로, 환율,...)   |   7 병합 및 분할 도구 (고급 결합 행, 셀 분할,...)   |   ... 그리고 더

Excel용 Kutools로 Excel 기술을 강화하고 이전과는 전혀 다른 효율성을 경험해 보세요. Excel용 Kutools는 생산성을 높이고 시간을 절약하기 위해 300개 이상의 고급 기능을 제공합니다.  가장 필요한 기능을 얻으려면 여기를 클릭하십시오...

상품 설명


Office Tab은 Office에 탭 인터페이스를 제공하여 작업을 훨씬 쉽게 만듭니다.

  • Word, Excel, PowerPoint에서 탭 편집 및 읽기 사용, Publisher, Access, Visio 및 Project.
  • 새 창이 아닌 동일한 창의 새 탭에서 여러 문서를 열고 만듭니다.
  • 생산성을 50% 높이고 매일 수백 번의 마우스 클릭을 줄입니다!

<p >

최고의 사무 생산성 도구

🤖 Kutools AI 보좌관: 다음을 기반으로 데이터 분석을 혁신합니다. 지능형 실행   |  코드 생성  |  사용자 정의 수식 만들기  |  데이터 분석 및 차트 생성  |  Kutools 기능 호출...
인기 기능: 중복 항목 찾기, 강조 표시 또는 식별   |  빈 행 삭제   |  데이터 손실 없이 열이나 셀 결합   |   수식없이 반올림 ...
슈퍼 조회: 다중 기준 VLookup    다중 값 VLookup  |   여러 시트에 걸친 VLookup   |   퍼지 조회 ....
고급 드롭다운 목록: 드롭다운 목록을 빠르게 생성   |  종속 드롭다운 목록   |  다중 선택 드롭 다운 목록 ....
열 관리자: 특정 개수의 열 추가  |  열 이동  |  Toggle 숨겨진 열의 가시성 상태  |  범위 및 열 비교 ...
특색 지어진 특징: 그리드 포커스   |  디자인보기   |   큰 수식 바    통합 문서 및 시트 관리자   |  리소스 라이브러리 (자동 텍스트)   |  날짜 선택기   |  워크 시트 결합   |  셀 암호화/해독    목록으로 이메일 보내기   |  슈퍼 필터   |   특수 필터 (굵게/기울임꼴/취소선 필터링...) ...
상위 15개 도구 세트12 본문 도구 (텍스트 추가, 문자 제거,...)   |   50+ 거래차트 유형 (Gantt 차트,...)   |   40+ 실용 방식 (생일을 기준으로 나이 계산,...)   |   19 삽입 도구 (QR 코드 삽입, 경로에서 그림 삽입,...)   |   12 매출 상승 도구 (숫자를 단어로, 환율,...)   |   7 병합 및 분할 도구 (고급 결합 행, 셀 분할,...)   |   ... 그리고 더

Excel용 Kutools로 Excel 기술을 강화하고 이전과는 전혀 다른 효율성을 경험해 보세요. Excel용 Kutools는 생산성을 높이고 시간을 절약하기 위해 300개 이상의 고급 기능을 제공합니다.  가장 필요한 기능을 얻으려면 여기를 클릭하십시오...

상품 설명


Office Tab은 Office에 탭 인터페이스를 제공하여 작업을 훨씬 쉽게 만듭니다.

  • Word, Excel, PowerPoint에서 탭 편집 및 읽기 사용, Publisher, Access, Visio 및 Project.
  • 새 창이 아닌 동일한 창의 새 탭에서 여러 문서를 열고 만듭니다.
  • 생산성을 50% 높이고 매일 수백 번의 마우스 클릭을 줄입니다!
</ p >

Comments (28)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Perfect, good job! A just not ajust with merge cells in the same colum, there is an error with this code on the script:

For exemple if i want ajust this range ("a32:i32"):

Call AutoFitMergedCells(Range("a32:i32"))

Apear an error in this line of the script:

.Rows(CStr(oRange.Row) & ":" & CStr(oRange.Row + oRange.Rows.Count - 1)).RowHeight = newHeight

Could you help me?
This comment was minimized by the moderator on the site
Hi All,

I modify the codes, which will search the merged cells and apply the autofit. hope this will help the future if any one interested.


Sub FindMergedCells()

' Declare sheet you want to look for merged cells on - in the example it's sheet 1
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets(1)
Dim rng As Range
Dim rngStart As Range
Dim rngEnd As Range
Dim tHeight As Integer
Dim iPtr As Integer
Dim oldWidth As Double
Dim oldZZWidth As Double
Dim newWidth As Double
Dim newHeight As Double
Dim oRange As Range


' Add sheet for output
Dim output As Worksheet
Set output = Sheets.Add(after:=Sheets(1))

' Initialize row counter for output
orow = 0

' Header on output sheet


' Check all the cells in the worksheet's used range
For Each cell In sheet.UsedRange

' If they're merged -

If cell.MergeCells Then
orow = orow + 1
Set cell = cell.MergeArea
Set rngStart = cell.Cells(1, 1)
Set rngEnd = cell.Cells(cell.Rows.Count, cell.Columns.Count)

'MsgBox "First Cell " & rngStart.Address & vbNewLine & "Last Cell " & rngEnd.Address
'output.Cells(orow, 1) = "" & Replace(rngStart.Address, "$", "") & ":" & Replace(rngEnd.Address, "$", "")
Set oRange = Range("" & Replace(rngStart.Address, "$", "") & ":" & Replace(rngEnd.Address, "$", ""))

With sheet
oldWidth = 0
For iPtr = 1 To oRange.Columns.Count
oldWidth = oldWidth + .Cells(1, oRange.Column + iPtr - 1).ColumnWidth
Next iPtr
'oldWidth = .Cells(1, oRange.Column).ColumnWidth + .Cells(1, oRange.Column + 1).ColumnWidth
oRange.MergeCells = False
newWidth = Len(.Cells(oRange.Row, oRange.Column).Value)
oldZZWidth = .Range("ZZ1").ColumnWidth
.Range("ZZ1") = Left(.Cells(oRange.Row, oRange.Column).Value, newWidth)
.Range("ZZ1").WrapText = True
.Columns("ZZ").ColumnWidth = oldWidth
.Rows("1").EntireRow.AutoFit
newHeight = .Rows("1").RowHeight / oRange.Rows.Count
.Rows(CStr(oRange.Row) & ":" & CStr(oRange.Row + oRange.Rows.Count - 1)).RowHeight = newHeight
oRange.MergeCells = True
oRange.WrapText = True
.Range("ZZ1").ClearContents
.Range("ZZ1").ColumnWidth = oldZZWidth
End With
Else

'MsgBox "Not merged area"

End If
Next cell

End Sub
This comment was minimized by the moderator on the site
I have tried this as I am not at all proficient with VBA. At the "Set Sheet = Activeworkbook I always get this Compile Error - Invalid outside procedure. What am I doing wrong?
This comment was minimized by the moderator on the site
Works perfectly on a single sheet. I need to fit multiple worksheet cells in one file. can you help me?
This comment was minimized by the moderator on the site
It works perfectly. However, I need to adjust the width of multiple worksheets. it's possible?
This comment was minimized by the moderator on the site
There is a limit on the size - if the total height required is greater than 409.5, it will only do what would fit in 409.5 and spread it amongst the height of the merged cells and you would not see the remainder.  I was hoping this would solve for text lengths greater than the max row height (409.5).  I think you may need to iterate through and split the text to what can fit in to the first max height of 409.5 then put the rest in another cell (ZZ2) and so on until it fits, then count the rows in each cell then get the total required height.
This comment was minimized by the moderator on the site
Dang it, copy/paste bit me. Also, with explicit sheet references the With isn't needed:

Public Sub AutoFitMergedCells(oRange As Range, ByVal dblWidth As Double)



oRange.MergeCells = False

Sheet1.Range("A1") = oRange.Cells(1, 1).Value

Sheet1.Range("A1").WrapText = True

Sheet1.Columns(1).ColumnWidth = dblWidth

Sheet1.Rows(1).EntireRow.AutoFit

oRange.Parent.Rows(oRange.Row).Resize(oRange.Rows.Count).RowHeight _

= Sheet1.Rows(1).RowHeight / oRange.Rows.Count

oRange.MergeCells = True

oRange.WrapText = True



End Sub
This comment was minimized by the moderator on the site
Thank you, that helped me with a sheet I've not been happy with for years.

I did change things around a bit, my merged cells are all in one column so I calculated that outside the loop and passed it. I also inserted a Sheet1 that is hidden, and manipulated the columns/rows there so as to not affect the sheet I'm working on. The references should probably be more explicit:

Public Sub AutoFitMergedCells(oRange As Range, ByVal dblWidth As Double)



Dim dblHeight As Double



With oRange.Parent

oRange.MergeCells = False

Sheet1.Range("A1") = oRange.Cells(1, 1).Value

Sheet1.Range("A1").WrapText = True

Sheet1.Columns(1).ColumnWidth = dblWidth

Sheet1.Rows(1).EntireRow.AutoFit

dblHeight = Sheet1.Rows(1).RowHeight / oRange.Rows.Count

oRange.Parent.Rows(oRange.Row).Resize(oRange.Rows.Count).RowHeight = newHeight

oRange.MergeCells = True

oRange.WrapText = True

Sheet1.Range("A1").ClearContents

End With



End Sub
This comment was minimized by the moderator on the site
This not work for me}
This comment was minimized by the moderator on the site
not working , ye password set in your code not working in your code
This comment was minimized by the moderator on the site
I believe the reason that the row heights do not calculate properly is related to these lines of code
For iPtr = 1 To oRange.Columns.Count
oldWidth = oldWidth + .Cells(1, oRange.Column + iPtr - 1).ColumnWidth
Next iPtr
oldWidth = .Cells(1, oRange.Column).ColumnWidth + .Cells(1, oRange.Column + 1).ColumnWidth

The variable OldWidth gets set to the sum of the column widths in the range, but for some reason it gets reset to only the width of the first two columns. The first 3 lines of code are therefore made redundant by the 4th line. When I removed the line it was much better, but the other issue I found was that you have to make sure that the font and font size of the temporary cell (ZZ1 in the example code) must match the font and size of the merged cells; otherwise, text will not wrap in the same way as the merged cells wrap and may not be the correct height.
This comment was minimized by the moderator on the site
I made add-in for Auto fit row height of multiple merged cells.
Please use this, if you want to autofit row hight.
[Release Ver2.6 · toowaki/AutoFitRowEx · GitHub]
https://github.com/toowaki/AutoFitRowEx/releases/tag/2.6.2
This comment was minimized by the moderator on the site
This is pretty helpful, thanks!
This comment was minimized by the moderator on the site
I am trying to understand the necessity of Line 19. You are assigning a value again to OldWidth. Can you please explain?
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations