2013-03-18 72 views
1

我有一个文件夹,其中包含许多文件,我需要:打开本周的文件,将它们存储在一个数组中,将它们传递给一个子文件,并通过它们循环以获取摘要信息。在Excel VBA宏中的数组

我可以从下面的代码中获取所需的日期文件。但是,代码抛出一个错误,将其存储在数组中并将其传递给数组。

Sub BatchProcessing() 
    firstday = Date - Weekday(Date) + 2 'To get the 1st day of week 
    lastday = Date - Weekday(Date) + 6 'To get the 5th day of week 
    MyPath = "P:\Data\"     'Path where my files were present  
    Dim Day 
    Dim strArray(0 To 5) As String 
    iCount=0 
     For Day = firstday To lastday  'To loop through all 5 day files 
      formatted_date = Format(Day, "yyyyMd") 
      MyTemplate = "TestFile" & formatted_date & ".xlsx" ' Set the template. 
      Workbooks.Open MyPath & MyTemplate 
      strArray(iCount) = ActiveWorkbook.Name 
      iCount = iCount+1  
     Next 

    CreateStats(strArray) 'Calling a sub which will do the required calculation 
End Sub 


Sub CreateStats(strArray As String) 
For Each element in strArray 
    set OriginalWorkbook = strArray(i) 
    'Do the processing' 
Next 
End Sub 
+1

什么是错误? – Sam 2013-03-18 20:53:03

+0

@Sam:我现在编辑了数组声明。但是,上面的代码现在将数组中的名称存储?以及如何传递它另一个功能? – Jill448 2013-03-18 21:23:38

+0

您应该在代码中设置一个断点,以查看数组是否按照您的预期填充,并且还要查看这些尺寸是否正确。要将它传递给子过程,必须将过程更改为接受数组作为参数。 – Sam 2013-03-18 21:31:13

回答

3

strArray变量是Single类型。如果您想要的变量是一个字符串数组,你必须声明它是这样:

Dim strArray(0 to 5) As String

编辑:

现在,你已经改变了你的代码中使用strArray() As String而非strArray As Single,你应该更新你的CreateStats子程序来接受一个数组作为参数。现在应该是这个样子:

Private Sub CreateStats(myArray() As String)

当你拥有了它,现在,你的程序只接受一个字符串。它必须接受一串字符串。一旦你有了,你可以遍历每个字符串并进行处理。

1

通过命名您的数组strArray看起来您将拥有一个字符串数组,实际上您尝试将工作簿名称存储在其中。但是,您将数组声明为Single,这是一种数字数据类型。根据CreateStats(strArray)子的做法,您可能需要将其从Single更改为String,或者可能需要设置另一个数组来保存Single,并且此数组保存String。