0

如何删除合并单元格的最左侧列而不删除其内容?

例如,range("A1:C1").value="Hi"

通过这样做range("A2").EntireColumn.delete(xlLeft),我不会丢失合并的单元格(现在变为range("A1:B1"),但我丢失了它的内容。

4

2 回答 2

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

这是你要找的吗?如果不是,请多解释一下。

于 2013-07-31T13:07:15.507 回答
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
于 2013-07-31T18:05:59.147 回答