如何通过excel中的vba表单链接文件

我创build了一个表单,允许用户单击一个button,然后它允许您浏览和查找您的文档或任何内容,并将其提交为与其他相关数据的链接。 我想知道如果他们是一种方式,让用户使链接连接到一个文件夹充满了多个文件,而不需要他们手动。 这是我的代码如下

Private Sub AddPicture_Click() Dim strFileToLink As String 'link name lnkNm = InputBox("please enter link description") Application.ScreenUpdating = False strFileToLink = Application.GetOpenFilename _ (Title:="Please select an Evidence file to link to") 'Checking if file is selected. If strFileToLink = "" Then 'Displaying a message if file not choosen in the above step. MsgBox "No file selected.", vbExclamation, "Sorry" 'And exiting from the procedure. Exit Sub Else 'print link to sheet as a hyperlink. erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row With ActiveSheet If ActiveSheet.Index >= 5 Then .Hyperlinks.Add Anchor:=Cells(erow, 12), _ Address:=strFileToLink, _ ScreenTip:="Picture Link", _ TextToDisplay:=lnkNm Else .Hyperlinks.Add Anchor:=Cells(erow, 13), _ Address:=strFileToLink, _ ScreenTip:="Picture Link", _ TextToDisplay:=lnkNm End If End With End If End Sub 

改善代码的意见也将非常感谢。 谢谢

而不是Application.GetOpenFileName使用Application.FileDialog ,它可以为文件夹或文件自定义等等。

https://msdn.microsoft.com/en-us/library/office/ff836226.aspx

以下是如何使用它来获取文件夹名称或文件名:

 Dim fdlg As FileDialog Dim fdlgType as Long, itm as Variant fdlgType = Application.InputBox("Enter '3' to choose a FILE, or '4' to choose a FOLDER") If fdlgType < 3 or fdlgType > 4 Then Exit Sub Set fdlg = Application.FileDialog(fdlgType) With fdlg .Title = IIf(fdlgType = 3, "Please select an Evidence FILE to link to", _ "Please select an Evidence FOLDER to link to") .ButtonName = IIf(fdlgType = 3, "Select File", "Select Folder") .Show For Each itm in .SelectedItems MsgBox itm Next End With 

FileDialog有一个.AllowMultiSelect属性,如果为真则让用户select多个文件(对文件夹不起作用)。 然后你可以遍历.SelectedItems

在您的代码中, For Each itm循环将包含添加超链接的代码:

 If .SelectedItems.Count = 0 Then MsgBox "Nothing selected.", vbExclamation, "Sorry" Exit Sub End If For Each itm in .SelectedItems 'print link to sheet as a hyperlink. With ActiveSheet erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row If .Index >= 5 Then .Hyperlinks.Add Anchor:=.Cells(erow, 12), _ Address:=itm, _ ScreenTip:="Picture Link", _ TextToDisplay:=lnkNm Else .Hyperlinks.Add Anchor:=.Cells(erow, 13), _ Address:=itm, _ ScreenTip:="Picture Link", _ TextToDisplay:=lnkNm End If End With Next 

而不是使用: –

 Application.GetOpenFilename(Title:="Please select an evidence file to link to") 

甚至: –

 Application.GetOpenFilename(Title:="Please select an evidence file to link to", MultiSelect:=True) 

以便他们可以select多个文件,如果需要,可以将每个文件添加为自己的订单项。

我会build议使用: –

 Application.FileDialog msoFileDialogFolderPicker 

对于文件夹select,和: –

 Application.FileDialog msoFileDialogFilePicker 

对于文件select,因为你没有错误,问题是: –

我想知道如果他们是一种方法,让用户使链接连接到一个文件夹充满了多个文件

上面的信息应该足以让你根据需要改变你的代码,我build议你的UserForm上有两个button,“链接文件”和“链接文件夹”。

如果在更改代码时发生错误,请随时发布(如果找不到答案),我相信人们会帮助您完成特定的查询。