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

时间:2016-04-19 07:51:27

标签: excel-vba vba excel

背景

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

挑战

通过使用保存单元格1内容的Variant临时变量来简单地交换,内容相当容易,用单元格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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

仅供记录,这里是我使用的最终代码(存储在我的Personal.xlsb中):

Public Sub SwapCellsGeneral(Optional bolWithFormat As Boolean = False)
    'Purpose: switch the content of two cells
    'Use Personal.xlsb to use a temporary cell and copy paste
    On Error GoTo ErrHandler
    Dim rngSel As Range, rngTemp As Range
    Dim varContent As Variant
    Set rngSel = Selection
    Set rngTemp = ThisWorkbook.Sheets(1).Cells(1, 1)
    If (rngSel.Count = 2) Then
        If (bolWithFormat) Then
            rngSel.Cells(1).Copy rngTemp
            rngSel.Cells(2).Copy rngSel.Cells(1)
            rngTemp.Copy rngSel.Cells(2)
        Else
            With rngSel.Cells(1)
                varContent = .Value
                .Value = rngSel.Cells(2).Value
                rngSel.Cells(2).Value = varContent
            End With
        End If
    Else
        'Do nothing, because swap make only sense for exactly 2 cells
    End If
ErrHandler:
    'Set this to avoid asking if we want to save personal.xlsb
    ThisWorkbook.Saved = True
    Set rngSel = Nothing
    Set rngTemp = Nothing
End Sub