【问题标题】:Store filehandles in array将文件句柄存储在数组中
【发布时间】:2016-05-10 09:47:51
【问题描述】:

我尝试打开指定文件夹中的所有*.xlsx 文件并将文件句柄存储在一个数组中。

我的代码是这样的

Dim Files() As Workbook
ReDim Files(Count)

File = Dir(Path & "\*.xlsx")
Count = 0

Do While File <> ""
    Set Files(Count) = Workbooks.Open(Path & File, , True)
    Count = Count + 1
    File = Dir()
Loop

代码似乎可以工作,但是,当我第二次运行它(再次点击运行按钮)时,我得到一个错误号 13。

调试代码我把问题跟踪到了一行

Set Files(Count) = Workbooks.Open(Path & File, , True)

由于我对 vba 不熟悉,我想我没有以正确的方式做到这一点......

将文件句柄存储到数组中特定文件夹中的所有文件的更好方法是什么?

【问题讨论】:

  • ...也许程序只是错过了要关闭的工作簿...我添加了Files(Count).Close() 解决了这个问题。
  • 但是那样你会错过刚刚存储在Files()中的Workbook对象引用...

标签: arrays vba file-handling filehandle


【解决方案1】:

您缺少路径分隔符

Set Files(Count) = Workbooks.Open(Path & "\" & File, , True)

【讨论】:

  • 谢谢,但Path 已经有尾部反斜杠... :(
  • 好吧,我不会这么说,因为你写的是File = Dir(Path &amp; "\*.xlsx")
【解决方案2】:

代码应该是:

Dim Files() As Workbook
Dim Count As Integer
ReDim Files(Count)

File = Dir(Path & "\*.xlsx")
Count = 0

Do While File <> ""
    ReDim Preserve Files(Count)
    Set Files(Count) = Workbooks.Open(Path & File, , True)
    Count = Count + 1
    File = Dir()
Loop

您需要重新调整阵列。 Preserve 保留现有数据。

【讨论】:

  • 您的第一个 Redim 应该被删除。每次重新调光对 VB 来说都是很多工作。
  • 谢谢,但数组大小不是问题(在我声明ReDim Files(Count)之前,我将文件夹中的文件数存储到Count)。我尝试了您的代码,但仍然收到 RuntimeError 13。我真的认为我在 Workbooks.Open 中有错误...
  • “(在我声明 ReDim Files(Count) 之前,我将文件夹中的文件数存储为 Count)。” -> 那Count = Count + 1for 是什么?
  • 是为了提高Files的索引
猜你喜欢
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
相关资源
最近更新 更多