複数のセルの値を操作する VSTO Excel アドインを作成しています。標準の Excel 機能を使用して、アドインによって作成された変更をユーザーが元に戻したりやり直したりできるようにしたいと考えています。VBA の使用は避けたいと思います。
これは可能ですか?もしそうなら、どのように?
別の質問: 既存の取り消し/やり直しスタックを調べることは可能ですか?
使用したい Excel/.NET/VSTO ランタイムのバージョンについては言及していませんが、それは実際には問題ではありません:]
VBA を注入しないと、カスタムの元に戻すことはできません。補正を使用するか (逆の操作)、または保存された状態を復元します。
VBAを避けたいと思っていることは知っていますが、他の人が述べたように、Undo
.
後で元に戻せるように、既存の選択をカスタム データ型として保持する VBA の例を次に示します。
Option Explicit
'Stores info about current selection'
Public OldWorkbook As Workbook
Public OldSheet As Worksheet
Public OldSelection() As SaveRange
'Custom data type for undoing'
Type SaveRange
Value As Variant
Address As String
End Type
Public Sub YourSubRoutine()
'A simple subroutine that acts on a Range selection'
Dim UserRange As Range
Set UserRange = Selection
If UserRange Is Nothing Then
Exit Sub
End If
'## The next block of statements '
'## Save the current values for undoing '
Set OldWorkbook = ActiveWorkbook
Set OldSheet = ActiveSheet
Application.ScreenUpdating = False
'## Code to manipulate the Selection range '
'## Code to manipulate the Selection range '
'## Code to manipulate the Selection range '
'## Specify the Undo Sub '
Application.OnUndo "Undo the YourSubRoutine macro", "UndoYourSubRoutine"
End Sub
Public Sub UndoYourSubRoutine()
Dim i As Integer
' Undoes the effect of the YourSubRoutine '
' Tell user if a problem occurs '
On Error GoTo Problem
Application.ScreenUpdating = False
'## Make sure the correct workbook and sheet are active '
OldWorkbook.Activate
OldSheet.Activate
'## Restore the saved information '
For i = 1 To UBound(OldSelection)
Range(OldSelection(i).Address).Value = OldSelection(i).Value
Next i
Exit Sub
' Error handler'
Problem:
MsgBox "Can't undo"
End Sub
以下を使用して、操作をスタックに追加できます。
Application.OnUndo text, procedureName
ここで、 Textは元に戻すコマンド ([編集] メニュー) で表示されるテキストであり、procedureNameはサブスクライブの 1 つの名前です。次を使用して、プログラムで操作を元に戻すこともできます。
Application.Undo
既存の元に戻す操作にアクセスすることはできないと思います。少なくとも私は聞いたことがありません。これを可能にするオンラインでアクセスできるライブラリがあるかもしれません。
お役に立てれば。
私が実際に行った解決策は次のとおりです。
明らかに、これはセル操作に限定されているため、任意の操作/コールバックを元に戻すスタックにプッシュすることはできません。また、私は Windows でのクリップボードの使用に関する原則に明らかに違反していますが、Microsoft がそのようなこと (ヒント) のためのより良い API を公開していれば、そうする必要はありません。
さらに、David Zemens の回答に対する最初のコメントで説明した解決策を採用しませんでした。これは、私たちの環境でいくつかのセキュリティ違反に遭遇したためです (つまり、ワークブックに VBA コードを挿入することは禁止されています)。
とにかく、みんなありがとう!