从剪贴板读取文件

从剪贴板读取文件

本文介绍了VBA:从剪贴板读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在VBA宏中加载文件,该文件是从资源管理器窗口复制而来的。

I'm trying to load a file in a VBA macro that has been copied from, say, an Explorer window.

我可以使用DataObject :: GetFromClipboard轻松地从剪贴板中获取数据,但是DataObject的VBA界面似乎没有除其他格式外的方法。纯文本。只有GetText和SetText方法。

I can easily get the data from the clipboard using DataObject::GetFromClipboard, but the VBA interface to DataObject doesn't seem to have methods for working with any other formats than plain text. There are only GetText and SetText methods.

如果我不能直接从DataObject获取文件流,文件名也可以,因此GetText可以被迫返回放置在剪贴板上的文件的名称?

If I can't get a file stream directly from the DataObject, the filename(s) would also do, so maybe GetText could be forced to return the name of a file placed on the clipboard?

在任何地方都找不到VBA的文档。 :(

There is very little documentation to be found for VBA anywhere. :(

也许有人可以将我指向具有这种功能的VBA API包装类?

Maybe someone could point me to an API wrapper class for VBA that has this sort of functionality?

推荐答案

这对我有用(在一个模块中);

This works for me (in a module);

Private Declare Function IsClipboardFormatAvailable Lib "user32" (ByVal uFormat As Long) As Long
Private Declare Function OpenClipboard Lib "user32" (ByVal Hwnd As Long) As Long
Private Declare Function GetClipboardData Lib "user32" (ByVal uFormat As Long) As Long
Private Declare Function CloseClipboard Lib "user32" () As Long
Private Declare Function DragQueryFile Lib "shell32.dll" Alias "DragQueryFileA" (ByVal drop_handle As Long, ByVal UINT As Long, ByVal lpStr As String, ByVal ch As Long) As Long

Private Const CF_HDROP As Long = 15

Public Function GetFiles(ByRef fileCount As Long) As String()
    Dim hDrop As Long, i As Long
    Dim aFiles() As String, sFileName As String * 1024

    fileCount = 0

    If Not CBool(IsClipboardFormatAvailable(CF_HDROP)) Then Exit Function
    If Not CBool(OpenClipboard(0&)) Then Exit Function

    hDrop = GetClipboardData(CF_HDROP)
    If Not CBool(hDrop) Then GoTo done

    fileCount = DragQueryFile(hDrop, -1, vbNullString, 0)

    ReDim aFiles(fileCount - 1)
    For i = 0 To fileCount - 1
        DragQueryFile hDrop, i, sFileName, Len(sFileName)
        aFiles(i) = Left$(sFileName, InStr(sFileName, vbNullChar) - 1)
    Next
    GetFiles = aFiles
done:
    CloseClipboard
End Function

使用:

Sub wibble()
    Dim a() As String, fileCount As Long, i As Long
    a = GetFiles(fileCount)
    If (fileCount = 0) Then
        MsgBox "no files"
    Else
        For i = 0 To fileCount - 1
            MsgBox "found " & a(i)
        Next
    End If
End Sub

这篇关于VBA:从剪贴板读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 08:02