【问题标题】:Undo changes function in Excel when using VBA in workbook在工作簿中使用 VBA 时撤消 Excel 中的更改功能
【发布时间】:2014-12-21 17:43:06
【问题描述】:

我的 Excel 工作簿中有以下 VBA 代码:

    Private Sub Worksheet_Change(ByVal Target As Range)
Target.Font.ColorIndex = 3
    If Target.Column = 1 Then
    Target.Interior.ColorIndex = 2
End If
End Sub

我发现,撤消功能丢失了。我在网上搜索了一下,发现是这样的:

Building Undo Into an Excel VBA Macro 但是,这只会撤消上次执行的 VBA 代码的更改,而不是在我的工作簿中不使用 VBA 代码所做的任何其他更改,例如撤消复制和粘贴

我已经在代码中添加了这个,但仍然没有运气!

Application.OnUndo "Primary Macro", "UndoPrimary"

这是我的 Mac 上出现的消息,与我使用 Windows7 PC 时出现的消息类似

http://s16.postimg.org/m8hi9i4qd/error.jpg

【问题讨论】:

  • 请发布您的undoPrimary的代码

标签: vba excel excel-formula


【解决方案1】:

为什么不保存状态?

'Create global arrays to store your colors in
Dim myColors() As String
Dim myFontColors() As String

'Create a function to save your state
Private Function SaveState(ByVal Target As Range)
    Dim x, index As Long
    index = 0

    'Make your arrays the same size as the target Range
    ReDim myColors(Target.Count)
    ReDim myFontColors(Target.Count)

    For Each x In Target.Cells
        myColors(index) = x.Interior.Color
        myFontColors(index) = x.Font.Color
        index = index + 1
    Next x
End Function

'Create a function to load your state
Private Function LoadState(ByVal Target As Range)
    Dim x, index As Long
    index = 0
    'Check to make sure the arrays have data in them first
    If UBound(myColors) = 0 Or Ubound(myFontColors) = 0 Then Exit Function

    For Each x In Target.Cells
        x.Interior.Color = myColors(index)
        x.Font.Color = myFontColors(index)
        index = index + 1
    Next x
End Function

Sub TestIt()
    Dim myRange As Range

    Set myRange = ActiveSheet.Range("A1:A12")
    SaveState myRange

    'I use a different column to see what's happening
    Set myRange = ActiveSheet.Range("B1:B12")
    LoadState myRange
End Sub

【讨论】:

  • 使用 x.Font.Color 代替 x.Interior.Color 来改变字体颜色。如果您想同时更改两者,只需添加一个 myFontColors() 数组,就像 myColors 数组一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
相关资源
最近更新 更多