2

场景:用户要求我为他们提供一个按钮,他们可以在其中选择 .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
4

2 回答 2

2

我不明白为什么app.Workbooks.Open会导致该错误。但是,我会建议一些可能会或可能不会帮助您识别问题的更改。

  1. 添加Option Explicit到模块的声明部分;然后从 VBE 主菜单运行 Debug->Compile 以显示哪些变量还没有变暗
  2. 包括app.Visible = True之后,Dim app As New Excel.Application以便您可以监控 Excel 发生的情况
  3. 在您的程序结束之前添加app.QuitSet app = Nothing
于 2010-11-03T21:54:57.963 回答
2

嗯..对我有用。

我注释掉了后面的四行app.Worksheets(1).ActivateMe![txtSelectedFile] = ...

set fd = Nothing不得不改变fdg

我想知道它自己的 Excel 文件是否有问题。你试过从头开始创建一个吗?

于 2010-11-03T22:05:14.580 回答