这类似于 Sid 的,只是让您双击任何单个单元格以打开文件对话框。
在一个模块中
Public Function getList(Optional ByVal Target As Range = Nothing) As String
Dim Dialog As FileDialog
Dim File As Integer
Dim Index As Integer
Dim List() As String
Dim Item As Integer
Dim Skip As Boolean
Set Dialog = Application.FileDialog(msoFileDialogFilePicker)
File = Dialog.Show
If File = -1 Then
' Get a list of any pre-existing files and clear the cell
If Not Target Is Nothing Then
List = Split(Target.Value, "|")
Target.Value = ""
End If
' Loop through all selected files, checking them against any pre-existing ones to prevent duplicates
For Index = 1 To Dialog.SelectedItems.Count
Skip = False
For Item = LBound(List) To UBound(List)
If List(Item) = Dialog.SelectedItems(Index) Then
Skip = True
Exit For
End If
Next Item
If Skip = False Then
If Result = "" Then
Result = Dialog.SelectedItems(Index)
Else
Result = Result & "|" & Dialog.SelectedItems(Index)
End If
End If
Next Index
' Loop through the pre-existing files and add them to the result
For Item = UBound(List) To LBound(List) Step -1
If Not List(Item) = "" Then
If Result = "" Then
Result = List(Item)
Else
Result = List(Item) & "|" & Result
End If
End If
Next Item
Set Dialog = Nothing
' Set the target output if specified
If Not Target Is Nothing Then
Target.Value = Result
End If
' Return the string result
getList = Result
End If
End Function
在您的工作表代码中
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Rows.Count = 1 And Target.Columns.Count = 1 Then getList Target
End Sub
更新
我改变了 getList 函数(它没有坏,只是让它做得更多)
- 它将允许您双击任何单元格,这将打开一个文件对话框。
- 您可以选择 1 个(或更多)文件
- 文件名将用“|”连接 字符并放入目标单元格
- 如果单元格中有任何预先存在的文件,则新文件将附加到它们
但是它不支持按回车键打开文件对话框,您必须双击单元格。
更新
以帮助 VMO(评论者)
工作表模块中的代码:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Rows.Count = 1 And Target.Columns.Count = 1 Then
If Target.Address = "$A$1" Then ' See Notes Below
Target.Value = getList(Target)
End If
End If
End Sub
要限制可以双击的单元格,您将需要使用类似的东西。您可以更改$A$1
为您想要的任何内容或找到一种方法来确定目标范围的名称(不太难)
如果您的工作表未锁定,则单击的单元格将保持焦点,并处于编辑模式,这有点烦人。锁定单元格,在以前版本的 excel 中修复了这个问题(我认为它在 v.2010+ 中不起作用)
模块 (getList) 中的代码可以保持几乎完全相同(尽管您可能希望删除所有处理多个文件的代码,但不是必需的)。您需要做的就是添加一行代码。
.......
Dim Skip As Boolean
Set Dialog = Application.FileDialog(msoFileDialogFilePicker)
Dialog.AllowMultiSelect = False ' This will restrict the dialogue to a single result
File = Dialog.Show
If File = -1 Then
......
希望这会有所帮助,我已经明白你在问什么!