gpt4 book ai didi

Excel VBA 在函数中合并单元格

转载 作者:行者123 更新时间:2023-12-02 18:41:03 26 4
gpt4 key购买 nike

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

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

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

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

我单击“确定”,Excel 崩溃、重新启动并再次提示该对话框。是否有其他方法使用 VBA 合并单元格 block ?

最佳答案

一般来说,合并单元格并不是一个好主意。这是一种修饰格式方法,可能会对 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

关于Excel VBA 在函数中合并单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13369195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com