mycode: -
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
合并到同一个单元格而不会丢失单元格中的数据(它们在每个单元格中都会有相同的数字((如同值/)当我运行我的代码时,它保存日期并合并单元格,但数字就像这样
但我希望它像这样(合并到一个单元格而没有边框。
我的代码中出错了什么?
答案 0 :(得分:1)
我无法想象为什么你会想要以这种方式合并细胞,但你却很接近。
由于您的范围是静态的,请明确定义您的范围。避免.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
您可以在线查找单元格外观属性列表,或者这是Google为我提供的第一个单元格。 here
您可以使用With功能快速将一系列格式应用到您的范围,而无需持续限定范围
With selectedcells
.Merge
.Value = Trim(cellText)
.WrapText = True
End With