我是VBA的新手,所以我不太清楚我在做什么。请善待。
我试图实现的是,用户从文件选择器中选择文件并将所选文件放入'路径到ArrayList。 我创建了fileList作为全局变量,然后在Workbook_Open事件中初始化它。
我在将String添加到ArrayList中时遇到Object variable or With block variable not set
错误。
Option Explicit
Dim fileList As Object
Sub Browse_Click()
Dim fd As FileDialog
Dim oFD As Variant
Dim Filepathname As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.ButtonName = "Select"
.AllowMultiSelect = True
.Filters.Add "CSV Files", "*.csv", 1
.Title = "Choose CSV File"
.InitialView = msoFileDialogViewDetails
.Show
For Each oFD In .SelectedItems
Filepathname = oFD
fileList.Add (Filepathname) // <~~~~~~~~~~~~~~~~~ ERROR HERE
Next oFD
Dim Str As Object
For Each Str In fileList
MsgBox Str
Next Str
End With
End Sub
Private Sub Workbook_Open()
Set fileList = CreateObject("System.Collections.ArrayList")
End Sub
修改 我想只初始化一次ArrayList。用户可以多次单击“浏览”按钮,我需要保留他在该ArrayList中选择的所有文件。
答案 0 :(得分:1)
通过这些更改代码对我有用:
Option Explicit
Dim fileList As Object
Sub Browse_Click()
Dim fd As FileDialog
Dim oFD As Variant
Dim Filepathname As String
Set fileList = CreateObject("System.Collections.ArrayList") 'Initialization moved here
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.ButtonName = "Select"
.AllowMultiSelect = True
.Filters.Add "CSV Files", "*.*", 1
.Title = "Choose CSV File"
.InitialView = msoFileDialogViewDetails
.Show
For Each oFD In .SelectedItems
Filepathname = oFD
fileList.Add (Filepathname)
Next oFD
Dim Str As Variant ' Changed to variant
For Each Str In fileList
MsgBox CStr(Str) ' Added conversion to string
Next Str
End With
End Sub