How to: Accept files dropped from File Explorer
Let users drag documents, images, or folders from File Explorer onto a grid record or a tree node, and store them the way your application needs: as records, as paths in a field, or as copies in a folder.
Requires WKL Forms Object Library 1.57 or later.
Solution overview
With AllowFileDrop = True, WklGrid, WklTreeList, WklGantt, and WklTreeView accept files from File Explorer.
While the user drags, FileDragOver reports each new target and lets you reject it with Cancel; after the drop,
FileDrop reports the full paths, the key of the target record or node, and the position. The control doesn't write
anything itself: your code in FileDrop decides what happens to the files, and Requery then shows the new records.
Implementation
A grid named grdDocuments shows the current customer's records from tblDocuments (ID AutoNumber, CustomerID,
FileName, FilePath). Dropped files become records for that customer; folders are rejected while dragging.
Private Sub Form_Load()
Me!grdDocuments.Object.AllowFileDrop = True ' or in the designer: page Behavior, card Files from Explorer
End Sub
Private Sub grdDocuments_FileDragOver(ByVal Files As Variant, ByVal TargetKey As Variant, _
ByVal Position As Long, Cancel As Integer)
Dim path As Variant
For Each path In Files
If (GetAttr(path) And vbDirectory) = vbDirectory Then Cancel = True: Exit Sub
Next
End Sub
Private Sub grdDocuments_FileDrop(ByVal Files As Variant, ByVal TargetKey As Variant, ByVal Position As Long)
Dim path As Variant
For Each path In Files
CurrentDb.Execute "INSERT INTO tblDocuments (CustomerID, FileName, FilePath) VALUES (" & Me!ID & ", '" & _
Replace(Mid$(path, InStrRev(path, "\") + 1), "'", "''") & "', '" & Replace(path, "'", "''") & "')", dbFailOnError
Next
Me!grdDocuments.Object.Requery
End Sub
Remarks
- Arguments:
Filesis a zero-based array of full paths (useFor EachorUBound).TargetKeyis the key of the record or node under the mouse pointer, orNullbelow the last one, on a group row, and on the new-record row.Positionis aWklDropPosition(wdpBefore,wdpAfter,wdpInside), so a tree can place a file before, after, or below a node. - Keep
FileDragOvershort. File Explorer waits for it while the user drags.FileDropruns after the drop is complete, so it can show messages, copy files, or prompt the user. - Files only. Text from Word, an email message from Outlook, or the control's own dragged nodes aren't files; the control rejects them without raising an event. To accept email messages or attachments, save them to a folder first.
- Form view only. In Design view and in reports, the control doesn't accept files.
- Event declarations: declare
PositionasLongor asWklDropPosition(which requires a reference to the WKL Forms Object Library);Cancelmust be passed by reference (Cancel As Integer). - The setting is saved with the form. It doesn't change
AllowDragDrop, which moves nodes within a tree.