我在Excel2010VBA (7.0)上创建了一个Userform
,它将通过.GetOpenFileName
属性传输用户选择的文件。然后将所选文件的文件路径插入到ListBox
中。
我的问题是,目前我正在尝试使用MultiSelect
,但是当我给.GetOpenFileName
Multiselect
属性将文件路径发送到我的ListBox
(这是启用了多行的)时,会出现一个为GetOpenFileName
代码行显示的类型不匹配错误。代码示例如下:
Private Sub CommandButton1_Click ()
Dim strFilePath As String
StrFilePath = Application.GetOpenFilename (,,,, MultiSelect:= True)
If strFilePath = "False" Then Exit Sub
FilesFrom.Value = strFilePath
End Sub
FilesFrom是列表框,我想让这些文件进入其中。我的代码允许用户选择单个文件并传输该文件,但它不允许我用多个文件填充这个列表框。
对于如何允许用户选择多个文件并将文件路径插入名为FilesFrom的列表框,有什么想法吗?
发布于 2016-02-25 04:34:44
问题是MultiSelect
返回一个Array
。
下面的代码应该是您想要的。它适合多种或单一选择。
Private Sub CommandButton1_Click()
'GetOpenFile MultiSelect will return an Array if more than one is selected
Dim FilePathArray As Variant
FilePathArray = Application.GetOpenFilename(, , , , MultiSelect:=True)
If IsArray(FilePathArray) Then
Dim ArraySize As Long
ArraySize = UBound(FilePathArray, 1) - LBound(FilePathArray, 1) + 1
Dim ArrayPosition As Long
For ArrayPosition = 1 To ArraySize
If Not FilePathArray(ArrayPosition) = Empty Then
'Replace "UserForm1" with the name of your Userform
UserForm1.FilesFrom.AddItem (FilePathArray(ArrayPosition))
End If
Next ArrayPosition
ElseIf FilePathArray <> False Then
'Replace "UserForm1" with the name of your Userform
UserForm1.FilesFrom.AddItem (FilePathArray)
End If
End Sub
发布于 2016-02-25 04:42:38
Application.GetOpenFilename对我来说似乎有点有限。我通常对下面的片段使用变体。它将所有选定的文件名复制到astrFiles()中,然后您可以根据需要处理该文件名。
Private Sub CommandButton1_Click()
Dim astrFiles() As String
Dim i As Integer
Dim varSelectedItem as Variant
Dim objFileSelect As FileDialog
Set objFileSelect = Application.FileDialog(msoFileDialogOpen)
objFileSelect.AllowMultiSelect = True
' Skip if user clicks cancel on dialogue
If objFileSelect.Show = True Then
' Copy from Variant() to String()
ReDim astrFiles(objFileSelect.SelectedItems.Count - 1)
For Each varSelectedItem In objFileSelect.SelectedItems
astrFiles(i) = varSelectedItem
i = i + 1
Next
End If
Set objFileSelect = Nothing
End Function
然后,您可以使用以下方法将结果加载到TextBox或类似文件中:
FilesFrom.Value = Join(astrFiles,vbCr)
https://stackoverflow.com/questions/35626944
复制