簡體   English   中英

當值相同時,如何合並同一行VBA中的相鄰單元格?

[英]How to merge adjacent cells in the same row VBA when the value is the same?

我是excel的VBA初學者,所以我需要幫助。

我必須合並同一列中的相鄰單元格,作為范圍變量,因為它總是會改變。

下圖顯示了我想要實現的目標:

在此輸入圖像描述

就像它的建議一樣,你需要循環通過列,並確定重復單元格之間的范圍,以便合並它們。

使用這樣的東西。

Option Explicit
Sub MergeCells()

Application.DisplayAlerts = False

Dim rng As Range
Dim LastColumn As Long
Dim ColumnsInRange As Long
Dim r As Long
Dim c As Long

'Last Column Used
LastColumn = ThisWorkbook.Sheets("Sheet1").Cells(3, Columns.Count).End(xlToLeft).Column

'Rows
For r = 3 To 4

'Columns
For c = 1 To LastColumn

Do While ThisWorkbook.Sheets("Sheet1").Cells(r, c) = ThisWorkbook.Sheets("Sheet1").Cells(r, c + 1)
ColumnsInRange = ColumnsInRange + 1
c = c + 1
Loop

Set rng = Range(Cells(r, c - ColumnsInRange), Cells(r, c))
rng.Select
With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Merge

    ColumnsInRange = 0

Next c

Next r

    Application.DisplayAlerts = True

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM