Excel VBA合并函数中的单元格

时间:2012-11-13 21:33:40

标签: excel excel-vba vba

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

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合并一个单元格块?

1 个答案:

答案 0 :(得分:3)

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

免责声明,提出一些建议

  • 使用Sub而不是函数,因为您希望使用更改范围
  • 使用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