Excel VBA将函数中的单元格合并

我写了一个粗略的函数来select和连接基于范围的单元格。

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 

在它内部,我试图合并单元格,当我运行的function,我得到一个提示说:

select包含多个数据值。 合并成一个单元格将只保留最左上angular的数据

我点击确定,Excel崩溃,重新启动,并再次提示对话框。 有没有另一种方法来合并使用VBA单元块?

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

除了免责声明,一些build议

  • 使用一个Sub而不是一个函数,因为你想要改变范围
  • 使用Application.DisplayAlerts来禁止合并单元格消息
  • 你可以显着减less代码

 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