简体   繁体   中英

Excel VBA merging cells in a function

I wrote a crude function to select and concatenate cells based on a range.

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

Within it I'm trying to merge the cells, when I run the function I get a prompt saying:

The selection contains multiple data values. Merging into once cell will keep the upper-left most data only

I click OK and Excel crashes, restarts, and prompts the dialog again. Is there another way to merge a block of cells using VBA?

Generally merging cells is not a good idea. It is a cosmetic formatting approach that can cause havoc with VBA code.

Disclaimers aside, a few suggestions

  • use a Sub rather than a Function given you want to work with altering the range
  • use Application.DisplayAlerts to suppress the merge cells message
  • you can cut down the code significantly

code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM