首页 > 解决方案 > 合并excel单元格不起作用

问题描述

我的代码:-

Public Sub CombineCells()
  'Use to mash all cells with there contents into one

  Dim selectedCells As Range
  Dim cell As Range
  Dim cellText As String

  Application.DisplayAlerts = False
  cellText = ""

  Set selectedCells = Selection
  For Each cell In selectedCells
    cellText = cellText & cell.Value & " "
  Next

  selectedCells.merge
  selectedCells.Value = Trim(cellText)
  selectedCells.WrapText = True
  Application.DisplayAlerts = True

End Sub

基本上我想将单元格从 A1 到 H6,Range A1:H6合并到同一个单元格中而不会丢失单元格中的数据(当我运行我的代码时,它们在每个单元格中都有相同的数字((如相同的值/)),它保存日期并合并单元格,但数字是这样的

在此处输入图像描述

但我希望它是这样的(合并到一个单元格中并且没有边界。

在此处输入图像描述

我在我的代码中做错了什么?

标签: vbaexcel

解决方案


我无法想象您为什么要以这种方式合并单元格,但您仍然很接近。

由于您的范围是静态的,请明确定义您的范围。尽可能避免.Selection& .Select

Sub Test()

Dim selectedCells As Range
Dim cell As Range
Dim cellText As String

Application.DisplayAlerts = False
cellText = ""

Set selectedCells = Range("A1:H6")
For Each cell In selectedCells
    cellText = cellText & cell.Value & " "
Next

selectedCells.Merge
selectedCells.Value = Trim(cellText)
selectedCells.WrapText = True
Application.DisplayAlerts = True

End Sub

你可以在网上找到细胞外观属性列表,或者这里是谷歌为我提取的第一个列表。这里

您可以使用 With 功能快速将一堆格式应用于您的范围,而无需连续限定范围

With selectedcells
    .Merge
    .Value = Trim(cellText)
    .WrapText = True
End With

推荐阅读