2

我有一个程序可以复制一系列单元格,并且需要将内容粘贴到用代码创建的新工作簿中。我可以复制数据,但是每当我将工作簿更改为新创建的工作簿时,剪贴板都会以某种方式丢失其数据。我考虑将单元格复制到数组中,然后将数组复制到新工作簿中,但在编码时我不知道数组的大小,这几乎每次宏运行时都会变化。我如何在更改活动工作簿时将数据保留在剪贴板上?

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 行丢失其内容

4

1 回答 1

1

Excel/VBA 中有一些操作会使选择/剪贴板无效,例如更改任何窗口/显示设置。因此,我怀疑当您更改工作表/工作簿时会调用一些事件。

您可以调试它,并在单步执行代码时找出选择何时无效并避免此语句(如果可能)。

或者,在您的事件代码中使用subStoreClipboard和from 下面的代码。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
于 2013-10-01T21:27:23.923 回答