在 Excel VBA 宏中组合两种类型的粘贴

Combine Two Types of Paste in an Excel VBA Macro

我希望将 Excel 中的默认粘贴设置为仅值或匹配目标格式。我知道如何为每个单独创建一个宏,但 xlPasteValues 仅在您从工作簿中的单元格复制时有效,并且匹配目标格式不起作用(但它在从网页复制时有效,这正是我想要的) .我的目标是创建一个结合了两者的 VBA 宏,这样我只需要使用一个命令,无论我是从单元格还是网页复制,它都会在没有任何源格式的情况下粘贴。

伪代码:

Sub SuperPaste()
     if clipboard source is a cell (or vice versa, whatever is easier):
          Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
               :=False, Transpose:=False
     else:
          ActiveSheet.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:= _
               False, NoHTMLFormatting:=True
(maybe some error handling)
End Sub

以下是您尝试执行的操作:

Sub SuperPaste()
     
''' Clipboard source is a current-instance excel cut:
''' - only option is to paste all (or throw an error msg)
    If Application.CutCopyMode = xlCut Then
        ActiveSheet.Paste
        
''' Clipboard source is a current-instance excel copy:
''' - paste values only (keeps destination formats)
''' - am pasting to the activecell to avoid mis-matched source and destination selections
    ElseIf Application.CutCopyMode = xlCopy Then
        ActiveWindow.ActiveCell.PasteSpecial xlPasteValues
            
''' Clipboard is empty: report to user
    ElseIf Application.ClipboardFormats(1) = -1 Then
        MsgBox "Nothing has been copied."

''' Clipboard source is another application (including another instance of excel):
''' - paste text (same as paste values for excel)
''' - still retains numbers (if tabbed or tabled apart) from word, html, another instance of excel, etc.
    Else: ActiveSheet.PasteSpecial Format:="Text"
    End If

End Sub

备注:

  1. 您可以通过声明用于使用剪贴板的 Lib 函数来做更复杂的事情
  2. 但是,上述方法适用于 99.9% 的您希望保留目标格式的副本类型

编辑:添加了对空剪贴板的处理