将单元格的完整格式存储在变量中

tho*_*hal 5 excel vba

背景

我想编写一个简单的函数来交换两个选定的(不一定是相邻的)单元格的内容。我不想先将单元格复制到临时单元格。因此,我真的很想将单元交换到位。

挑战

虽然通过使用保存Variant单元格 1 内容的临时变量,用单元格 2 的内容覆盖单元格 1 的内容,然后将变量变量的内容写回单元格 2,简单地交换内容相当容易,但我很难如何还复制所有格式相关的内容。有很多插槽需要考虑(.NumberFormat, .Interior仅举两个)。我真的需要单独复制它们吗?还是有更简单的方法来交换格式而不使用任何临时单元格?

代码

Public Sub SwapCells(Optional bolWithFormat As Boolean = True)
    'Purpose: switch the content of two cells
    On Error GoTo ErrHandler
    Dim rngSel As Range
    Dim varContent As Variant
    Set rngSel = Selection
    If (rngSel.Count = 2) Then
        With rngSel.Cells(1)
            varContent = .Value
            .Value = rngSel.Cells(2).Value
            rngSel.Cells(2).Value = varContent
        End With
    Else
        'Do nothing, because swap makes only sense for exactly 2 cells
    End If
ErrHandler:
    Set rngSel = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

Ror*_*ory 3

根据评论,使用临时拘留室是最简单的解决方案。您可以使用个人宏工作簿中的单元格,以避免担心在活动工作簿中找到备用单元格。之后将个人工作簿的属性设置为 True 可能是明智的做法Saved,以避免每次运行宏后退出 Excel 时都提示保存该工作簿!