如何删除合并单元格的最左侧列而不删除其内容?
例如,range("A1:C1")
与.value="Hi"
通过执行range("A2").EntireColumn.delete(xlLeft)
,我不会丢失合并的单元格(现在变为range("A1:B1")
,但我丢失了内容。
答案 0 :(得分:2)
为什么不将值保存在临时变量中:
Sub DeleteColumnRetainMergedCellValue()
'Select merged cells, then run this subroutine.
Dim v As String
v = Selection.Cells(1, 1).Value
Selection.Cells(1, 1).EntireColumn.Delete
Selection.Cells(1, 1).Value = v
End Sub
这是你要找的吗?如果没有,请再解释一下。
答案 1 :(得分:1)
我不得不处理未知的合并单元格地址。以下是我对变量范围的解决方案:
'' The Microsoft Scripting Runtime must be activated for this to work
'' Assumes rngDelete contains only one column
Sub DeleteColumnRetainMergedCellValues(rngDelete As Range)
Dim dicMerged As Dictionary
Set dicMerged = New Dictionary
Dim key As Variant
Dim rngCell As Range
Dim rngColumn As Range
Dim rngOptimizedColumn As Range
'' optimize the search range
Set rngColumn = rngDelete.EntireColumn
Set rngOptimizedColumn = Range( _
rngColumn.Cells(1, 1), _
rngColumn.Cells(rngColumn.Rows.Count, 1).End(xlUp))
'' find all merged cells, store their addresses and values
For Each rngCell In rngOptimizedColumn.Cells
If rngCell.MergeArea.Cells.Count > 1 Then
dicMerged.Add _
rngCell.MergeArea.Cells(1, 1).Address, _
rngCell.MergeArea.Cells(1, 1).Value
End If
Next rngCell
'' delete the column
rngDelete.EntireColumn.Delete (xlLeft)
'' paste back the value in the merged cells
For Each key In dicMerged
Range(key).Value = dicMerged(key)
Next key
End Sub