我正在想办法备份数据,以便在需要时恢复。在UserForm初始化期间,我正在进行
'Save Backup
Worksheets("Machine Format").Cells(ActiveCell.Column).EntireColumn.copy
如果不是整列而是只有带数据的行,那将是更可取的,但我不知道如何将此代码与结合起来
Dim LastRow As Long
LastRow = Range("B" & Rows.Count).End(xlUp).Row
然而,当我试图用粘贴以前复制的数据时,我能想到的一切都不起作用
'Paste Backup
ActiveSheet.Paste Destination:=Worksheets("Machine Format").Cells(ActiveCell.Column)
它不会粘贴它,也不会显示任何错误。我甚至不确定像这样备份数据的概念是最佳还是好主意。
有人能帮我解决这个问题吗?我甚至需要这个的原因是,我有一个可以实时修改数据的用户表单,当通过X按钮关闭用户表单时,我需要它来取消所有更改,我想我可以在初始化用户表单时复制数据,然后在通过X按钮关闭用户表单时将其粘贴回。
您可以将值保存在数组中
Dim BackupArray() As Variant
BackupArray = Worksheets("Machine Format").UsedRange.Value
如果你必须退货,你可以使用
Worksheets("Machine Format").Cells(row, column).Value = BackupArray(row, column)
从备份中返回特定值,或一次还原整个值:
Worksheets("Machine Format").UsedRange.Value = BackupArray
请注意,这仅适用于更改的值。如果添加了新值,并且您也想删除它们,则需要首先清除所有单元格的内容,然后恢复到原始范围:
Dim OriginalDataRange As Range
Set OriginalDataRange = Worksheets("Machine Format").UsedRange
Dim BackupArray() As Variant
BackupArray = OriginalDataRange.Value
' do your changes here
' revert entire backup
Worksheets("Machine Format").UsedRange.ClearContents 'remove changed data including new added data
OriginalDataRange.Value = BackupArray ' revert old tata
如果创建备份和恢复不是在同一过程中进行的,请将BackupArray
设为公共变量。
请注意,如果使用End
语句(不要与End Sub
混淆!(意外停止整个VBA运行,则备份数据将丢失。它只在VBA运行时(或者更好的是在变量BackupArray
的生存期内(持续存在。
备份列数据
Option Explicit
Private bData As Variant ' Array
Private brg As Range ' Column Range (object)
Sub UsageExample()
' Some code...
backupData
' some more code...
If Something Then
' Whatever...
Else
retrieveData
End If
End Sub
Sub backupData()
Const wsName As String = "Machine Format"
Const First As Long = 2
Const lrCol As String = "B"
Dim wb As Workbook: Set wb = ThisWorkbook
With wb.Worksheets(wsName)
.Activate
If TypeName(Selection) = "Range" Then
' Create a reference to the column range.
Dim Last As Long: Last = .Range("B" & .Rows.Count).End(xlUp).Row
Dim cCol As Long: cCol = Selection.Cells(1).Column
Set brg = .Columns(cCol).Rows(First & ":" & Last)
' Write the values from the column range to an array.
If brg.Cells.Count = 1 Then
ReDim bData(1 To 1, 1 To 1): bData(1, 1) = brg.Value
Else
bData = brg.Value
End If
'Else
' No range selected.
End If
End With
End Sub
Sub retrieveData()
If Not brg Is Nothing Then
Debug.Print brg.Address
Debug.Print UBound(bData, 1), UBound(bData, 2)
' Write data back to range.
brg.Value = bData
Else
Debug.Print "No range."
End If
End Sub