【问题标题】:Excel Copy a range of cell values to the clipboardExcel 将一系列单元格值复制到剪贴板
【发布时间】:2018-02-06 13:08:54
【问题描述】:

我想将一系列单元格(仅值/文本)复制到剪贴板,这样用户就不必仅在将特殊值粘贴到另一个电子表格时才粘贴它们。

这是我目前所拥有的:

Private Sub CommandButton1_Click()
    With New DataObject
        .SetText Range("A32:Q32").Text
        .PutInClipboard
    End With
    'Range("A32:Q32").Copy
End Sub

这给了我一个运行时错误

94 无效使用 Null

如果我只使用注释掉的代码Range.("A32:Q32").Copy,它会复制公式,除非用户进行特殊粘贴,否则会出现各种参考错误。

【问题讨论】:

  • 两个答案都有效。一个回答了我最初的需求,第二个想出了一个更巧妙的方法来做到这一点。谢谢!

标签: vba excel


【解决方案1】:

这有点复杂,但是获取文本 > 清除剪贴板 > 放回文本:

[A32:Q32].Copy
With New DataObject
    .GetFromClipboard
    s = .GetText
    .Clear
    .SetText s
    .PutInClipboard
End With

当范围内的各个单元格文本不同时,Range.Text 返回Null

【讨论】:

  • 似乎不需要Application.CutCopyMode = False,因为剪贴板内容已被.PutInClipboard覆盖
  • @gbarnabic 如果我没记错的话,如果您在复制区域仍处于活动状态时粘贴到同一个 Excel 应用程序实例中,Excel 可以忽略剪贴板而只使用剪切/复制范围
  • @gbarnabic 你是对的.. 剪切/复制选择在.PutInClipboard 之后消失了
【解决方案2】:

我不知道数据对象,所以我提出了一个解决方法,让用户也选择目标单元格

Private Sub CommandButton1_Click()
    Dim userRng As Range
    With ActiveSheet 'reference currently active sheet, before the user could change it via inputbox 
        Set userRange = GetUserRange()
        If Not userRange Is Nothing Then ' if the user chose a valid range
            With .Range("A32:Q32")
                userRange.Resize(.Rows.Count, .Columns.Count).Value =.Value ' paste values only
            End With
        End If
    End With
End Sub


Function GetUserRange() As Range   
' adapted from http://spreadsheetpage.com/index.php/tip/pausing_a_macro_to_get_a_user_selected_range/

    Prompt = "Select a cell for the output."
    Title = "Select a cell"

    '   Display the Input Box
    On Error Resume Next
    Set GetUserRange = Application.InputBox( _
        Prompt:=Prompt, _
        Title:=Title, _
        Default:=ActiveCell.Address, _
        Type:=8) 'Range selection

'   Was the Input Box canceled?
    If GetUserRange Is Nothing Then MsgBox “Canceled!”
End Function

【讨论】:

  • 不是我问的,但我最终使用了它。谢谢!
  • 不客气。那么您实际采用了哪种解决方案?
  • 我两个都用过。我将范围复制到剪贴板,然后实现了您的代码。在提示符下,我指出数据已复制到剪贴板,但如果他们愿意,他们可以选择一个单元格来粘贴它。正如我发现在 VBA 代码中执行此操作会清除“撤消缓冲区”,因此无法返回。使用剪贴板方法,Ctrl-Z 将它们粘贴到错误的位置。我想我会让用户选择哪种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多