在Excel VBA中的多个工作表中动态标注数组?

时间:2016-05-12 06:34:39

标签: arrays excel excel-vba vba

我有6个工作表,每个工作表都有一个数据的子类别(重要的是它们在单独的工作表中)。我正在将数据加载到数组中,因为有数千行,然后以特定格式将它们打印到.txt文件中。

Sub ExcelToXML()

Dim headers(), data(), attributes1(), attributes2(), attr$, r&, c&
Dim rowCount As Long
Dim columnCount As Long
Dim FF As Worksheet
Dim FOPR As Worksheet
Dim R1 As Long
Dim C1 As Long

Set FF = Worksheets("Fairy")
Set FOPR = Worksheets("Opera")

rowCount = (FF.Range("A1048576").End(xlUp).Row) 'Only one defined as rowCount should be consistent

ffcolumncount = (FF.Range("XFD1").End(xlToLeft).Column) 
FOPRcolumnCount = FOPR.Range("XFD1").End(xlToLeft).Column


' load the headers and data to an array '
FFheaders = Cells(1, 1).Resize(1, ffcolumncount).Value
FFdata = Cells(1, 1).Resize(rowCount, ffcolumncount).Value

FOPRheaders = Cells(1, 1).Resize(1, FOPRcolumnCount).Value
FOPRdata = Cells(1, 1).Resize(rowCount, FOPRcolumnCount).Value


' set the size for the attributes based on the columns per child, dynamic
ReDim attributes1(1 To ffcolumncount)
ReDim attributes2(1 To FOPRcolumnCount)

' open file and print the header two main parents
Open "C:\desktop\ToGroup.xml" For Output As #1 'file path is here, going to change to save prompt
Print #1, "<Parent>"
Print #1, "  <Child>"

' iterate each row non inclusive of headers 
For r = 2 To UBound(FFdata)

  ' iterate each column '
  For c = 1 To UBound(FFdata, 2)
    ' build each attribute '
    attr = FFheaders(1, c) & "=""" & FFdata(r, c) & """"
    attributes1(c) = FFheaders(1, c) & "=""" & FFdata(r, c) & """"

    Next

       For R1 = 2 To UBound(FOPRdata)

         For C1 = 1 To UBound(FOPRdata, 2)

             attr = FOPRheaders(1, c) & "=""" & FOPRdata(r, c) & """"
             attributes2(c) = FOPRheaders(1, c) & "=""" & FOPRdata(r, c) & """"
                Next

我在prining处切断它,在2处切断下一个循环。 (实际上并不确定for..next循环是否正确构造)。无论如何,我的问题是,我的重新定标是错误的吗?它在第二个属性上给出了'下标超出范围'错误。是行

ReDim attributes2(1 To FOPRcolumnCount)
问题是什么?因为它可能在原始工作表中标注数组的大小。也许我应该在单独的或工作表模型中定义数组?我可以和我如何参考它们?有没有办法让数组专门引用工作表?

感谢任何输入。没有任何人可以提供第二意见真的很难。

1 个答案:

答案 0 :(得分:0)

尝试用实际值替换'FOPRcolumnCount'。如果它解决了你的问题,那么问题在于如何计算“FOPRcolumnCount”,我认为这就是你的问题所在。从你的例子中很难说,但看起来你正试图在第1行找到最合适的专栏;有更简单的方法。与rowCount相同。

我注意到你没有将它声明为变量。 始终声明您的变量;将“Option Explicit”放在模块的顶部以强制您声明所有变量。