這與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個(或更多)文件
- 文件名將與「|」特點,並提出在靶細胞
- 如果預先存在的任何文件都在細胞內,新的會被追加到它們
但是,它並不支持按Enter,打開文件對話框中,必須雙擊該單元格。
更新 爲了幫助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
要限制單元格是雙click'able,你將需要使用類似的東西。你可以改變$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
......
希望這會有所幫助,我明白你在問什麼!
我複製了你的代碼在vba代碼中爲sheet1 ...但它沒有工作..沒有行1和列1 ...我把'MsgBox'作爲測試,但似乎,它不運行代碼! – Amir
您是否還添加了新的代碼模塊並將其他代碼塊放入? – NickSlash
我添加了'module1'並且放置了'Public Function getList ...',然後在vba頁面上雙擊'sheet1',然後將'Private Sub Worksheet_BeforeDoubleClick ...'放入其中。 – Amir