我在excel 2010 VBA(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的列表框中的任何想法?
答案 0 :(得分:1)
问题在于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
答案 1 :(得分:0)
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)