我有一个程序可以复制一系列单元格,并且需要将内容粘贴到代码中创建的新工作簿中。我可以复制数据,但每当我将工作簿更改为新创建的工作簿时,剪贴板就会丢失其数据。我考虑将单元格复制到一个数组,然后只是将数组复制到新的工作簿,但我不知道在编码时数组的大小,这几乎每次宏运行时都会有所不同。 当我更改活动工作簿时,如何将数据保留在剪贴板上?
cell = "k7: l" & row
Worksheets(1).Range(cell).Select
Selection.Copy
relpath = ThisWorkbook.Path & "\" & "DispersionList.xls"
If Dir(relpath) <> "" Then
Application.Workbooks.Open (relpath)
Workbooks("DispersionList.xls").Activate
Else
Call createWorkbook
End If
Worksheets(1).Cells(7, 14).Select
Selection.PasteSpecial
End Sub
如果我逐行遍历代码并检查剪贴板,它会在workbooks.open行中丢失其内容
答案 0 :(得分:1)
Excel / VBA中有一些操作会使选择/剪贴板无效,例如更改任何窗口/显示设置。因此,我怀疑在更改工作表/工作簿时会调用某个事件。
您可以调试它并在逐步完成代码计算时,当选择无效时避免使用此语句(如果可能)。
或者,在事件代码中使用以下代码中的subStoreClipboard
和subRestoreClipboard
。要使用代码,请将其插入工作表中的新模块中 - 并在VBA中插入名为“ws_Temp”的新(隐藏)工作表。
Private mIntCutCopyMode As XlCutCopyMode
Private mRngClipboard As Range
Public Sub subStoreClipboard()
On Error GoTo ErrorHandler
Dim wsActiveSource As Worksheet, wsActiveTarget As Worksheet
Dim strClipboardRange As String
mIntCutCopyMode = Application.CutCopyMode
If Not fctBlnIsExcelClipboard Then Exit Sub
Application.EnableEvents = False
'Paste data as link
Set wsActiveTarget = ActiveSheet
Set wsActiveSource = ThisWorkbook.ActiveSheet
With ws_Temp
.Visible = xlSheetVisible
.Activate
.Cells(3, 1).Select
On Error Resume Next
.Paste Link:=True
If Err.Number Then
Err.Clear
GoTo Finalize
End If
On Error GoTo ErrorHandler
End With
'Extract link from pasted formula and clear range
With Selection
strClipboardRange = Mid(.Cells(1, 1).Formula, 2)
If .Rows.Count > 1 Or .Columns.Count > 1 Then
strClipboardRange = strClipboardRange & ":" & _
Mid(.Cells(.Rows.Count, .Columns.Count).Formula, 2)
End If
Set mRngClipboard = Range(strClipboardRange)
.Clear
End With
Finalize:
wsActiveSource.Activate
wsActiveTarget.Parent.Activate
wsActiveTarget.Activate
ws_Temp.Visible = xlSheetVeryHidden
Application.EnableEvents = True
Exit Sub
ErrorHandler:
Err.Clear
Resume Finalize
End Sub
Public Sub subRestoreClipboard()
Select Case mIntCutCopyMode
Case 0:
Case xlCopy: mRngClipboard.Copy
Case xlCut: mRngClipboard.Cut
End Select
End Sub
Private Function fctBlnIsExcelClipboard() As Boolean
Dim var As Variant
fctBlnIsExcelClipboard = False
'check if clipboard is in use
If mIntCutCopyMode = 0 Then Exit Function
'check if Excel data is in clipboard
For Each var In Application.ClipboardFormats
If var = xlClipboardFormatCSV Then
fctBlnIsExcelClipboard = True
Exit For
End If
Next var
End Function