3

我编写了一个粗略的函数来根据范围选择和连接单元格。

Function GetSkills(CellRef As String, CellRefEnd As String, Delimiter As String)

    Dim CellStart As Range
    Dim CellEnd As Range
    Dim LoopVar As Long
    Dim StartRow As Long
    Dim EndRow As Long
    Dim Concat As String
    Dim Col As Long

    Set CellStart = Worksheets(1).Cells.Range("B" & CellRef)
    Set CellEnd = Worksheets(1).Cells.Range("B" & CellRefEnd)

    Col = CellStart.Column
    StartRow = CellStart.Row
    EndRow = CellEnd.Row

    With Range(CellStart, CellEnd)
        .Merge
        .WrapText = True
    End With

    Concat = ""

    For LoopVar = StartRow To EndRow
        Concat = Concat & Cells(LoopVar, Col).Value
        If LoopVar <> EndRow Then Concat = Concat & Delimiter & " "
    Next LoopVar

    GetSkills = Concat

End Function

在其中我试图合并单元格,当我运行该函数时,我得到一个提示:

选择包含多个数据值。合并到一次单元格将仅保留左上角的大部分数据

我单击“确定”,Excel 崩溃、重新启动并再次提示对话框。是否有另一种方法可以使用 VBA 合并单元格块?

4

1 回答 1

3

通常合并单元格不是一个好主意。这是一种外观格式化方法,可能会对 VBA 代码造成严重破坏。

除了免责声明,还有一些建议

  • 鉴于您想要更改范围,请使用 Sub 而不是 Function
  • 用于Application.DisplayAlerts抑制合并单元格消息
  • 您可以显着减少代码

代码

Sub Test()
Call GetSkills(2, 4, ",")
End Sub

Sub GetSkills(CellRef As String, CellRefEnd As String, Delimiter As String)
Dim CellStart As Range
Dim CellEnd As Range
Dim Concat As String

Application.DisplayAlerts = False
Set CellStart = Worksheets(1).Cells.Range("B" & CellRef)
Set CellEnd = Worksheets(1).Cells.Range("B" & CellRefEnd)

Concat = Join(Application.Transpose(Range(CellStart, CellEnd)), Delimiter)

With Range(CellStart, CellEnd)
    .Merge
    .WrapText = True
    .Value = Concat
End With
Application.DisplayAlerts = True
End Sub
于 2012-11-13T22:22:32.303 回答