怎样根据某一列内容合并单元格——针对数据库的表头和表体

本文介绍了一个使用VBA实现Excel中特定范围单元格合并的示例代码。该代码通过定义一个公共函数来实现对指定范围内单元格的合并操作,并保持合并后的单元格内容居中对齐。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Public Function mergePeicangOrderNo(strRange As String, intRange As Integer)
    Dim rng As Range
    Dim cellRange As Range
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer
    Dim n As Integer
    Dim sht As Worksheet
    Dim arr As Variant

    arr = Array(2, 3, 4, 5, 6, 7, 8)
    Set sht = ActiveSheet
    Set rng = sht.Range(strRange & intRange)
    rng.Select
    Set cellRange = sht.UsedRange
    j = 1
    For i = intRange To cellRange.Rows.Count - intRange + 1
        If sht.Cells(i + 1, strRange) = rng Then
            j = j + 1
            rng.Resize(j, 1).Select

        Else:
            Application.DisplayAlerts = False
            Selection.Merge '首先合并单元格
            Selection.HorizontalAlignment = xlCenter
            Selection.VerticalAlignment = xlCenter
            For k = 0 To UBound(arr)
                Set rng = rng.Offset(0, arr(k) - 1)
                rng.Resize(j, 1).Select
                Selection.Merge
                Selection.HorizontalAlignment = xlCenter
                Selection.VerticalAlignment = xlCenter
                Set rng = rng.Offset(0, 1 - arr(k))
                rng.Select
            Next k
            Application.DisplayAlerts = True
            Set rng = sht.Range(strRange & i + 1) '设置单元格为最下面的下一个
            rng.Select
            j = 1 'j重新为第一个
        End If
        If ((i = cellRange.Rows.Count - intRange + 1) And (j > 1)) Then
            Application.DisplayAlerts = False
            Selection.Merge '首先合并单元格
            Selection.HorizontalAlignment = xlCenter
            Selection.VerticalAlignment = xlCenter
            For k = 0 To UBound(arr)
                Set rng = rng.Offset(0, arr(k) - 1)
                rng.Resize(j, 1).Select
                Selection.Merge
                Selection.HorizontalAlignment = xlCenter
                Selection.VerticalAlignment = xlCenter
                Set rng = rng.Offset(0, 1 - arr(k))
                rng.Select
            Next k
        End If

    Next i
End Function
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值