场景:用户要求我提供一个按钮,用户可以选择.xls,然后将数据导入到表格中的相应列中。
问题:我将提供以下代码,但基本上一旦它尝试打开工作簿,它就会给我下面的错误。我已经搜索了许多解决方案,但我仍然收到此错误。
Private Sub Command20_Click()
Dim fdg As FileDialog, vrtSelectedItem As Variant
Dim strSelectedFile As String
Set fdg = Application.FileDialog(msoFileDialogFilePicker)
With fdg
.AllowMultiSelect = False
.ButtonName = "Select"
.InitialView = msoFileDialogViewList
.Title = "Select Input Files"
'add filter for excel
With .Filters
.Clear
.Add "Excel Spreadsheets", "*.xls"
End With
.FilterIndex = 1
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems 'onby be 1
Dim app As New Excel.Application
app.Workbooks.Open (vrtSelectedItem)
app.Worksheets(1).Activate
For Each rwRow In ActiveWorkbook.Worksheets(1).Rows
' Do things with the rwRow object
Next rwRow
strSelectedFile = vrtSelectedItem
Next vrtSelectedItem
Me![txtSelectedFile] = strSelectedFile
Else 'The user pressed Cancel.
End If
End With
Set fd = Nothing
End Sub
答案 0 :(得分:2)
我不明白为什么app.Workbooks.Open
会导致错误。但是,我会建议一些可能会或可能不会帮助您确定问题的更改。
Option Explicit
添加到模块的声明部分;然后从VBE主菜单运行Debug-> Compile,以显示哪些变量没有Dim'd app.Visible = True
之后加入Dim app As New Excel.Application
,以便您可以监控Excel发生的情况app.Quit
和Set app = Nothing
答案 1 :(得分:2)
嗯..从我身上起作用。
我在app.Worksheets(1).Activate
和Me![txtSelectedFile] = ...
set fd = Nothing
我必须更改为fdg
我想知道Excel文件是否有问题。你尝试过从头创建的吗?