如何使用循环为数组赋值

时间:2015-10-24 15:04:19

标签: arrays excel vba excel-vba

  

我想使用循环

从工作表中为数组赋值      

我尝试使用此功能但出现错误“下标超出范围”

std::bind([](){})
  

我尝试了两种方式进行初始化,但没有一种方法可以使用

     

初始化类型1

 i=1
 With ws
        Do While i <= 40
            ReDim Preserve WorkID(1 To i)
            ReDim Preserve Work(1 To i)
            ReDim Preserve ComposerName(1 To i)

            WorkID(i) = Range("A" & i + 1).Value
            Work(i) = Range("B" & i + 1).Value
            ComposerName(i) = Range("C" & i + 1).Value
        i = i + 1
        Loop
    End With
  

初始化类型2

Dim WorkID() As Variant              
Dim Work() As Variant                
Dim ComposerName() As Variant
  

我也试过没有Dim WorkID(1 to 40) As Variant Dim Work(1 to 40) As Variant Dim ComposerName(1 to 40) As Variant 这样但没有任何效果:

Redim
  

Full Sub here:

   i=1
   With ws
        Do While i <= 40
            WorkID(i) = Range("A" & i + 1).Value
            Work(i) = Range("B" & i + 1).Value
            ComposerName(i) = Range("C" & i + 1).Value
        i = i + 1
        Loop
    End With

2 个答案:

答案 0 :(得分:3)

RedDim Preserve通常是一项昂贵的操作,因为它涉及为更大的数组分配空间并从旧数组中移动内容。在循环中使用它几乎总是一个坏主意。相反 - 提前确定数组需要多大,ReDim只需一次。如果您事先不知道,请将它们设置得比需要的大,然后在循环后使用ReDim Preserve将它们调整到适当的大小。在你的情况下,我会在进入for循环之前重新整理数组(甚至 - 为什么不Dim它们的大小合适?)。此外 - 使用适当的工作表变量为每个范围添加前缀,而不是依次激活每个范围。类似的东西:

Sub Join()

Dim WorkID()             'Stores the workID from Works Sheet
Dim Work()                 'Stores the work from Works Sheet
Dim ComposerName()       'Stores the composer from Works Sheet
Dim ConductorID()          'Stores the ConductorID from Conductors Sheet
Dim ConductorNames()       'Stores Conductor Names from Conductors Sheet
Dim CDWorkID()           'Stores CDWorkID  from CD Sheet
Dim CDCondID()                 'Stores CDConductor ID  from CD Sheet

Dim i As Long
Dim ws, wcon, wcd, wj As Worksheet

Set ws = Sheets("Works")
Set wcon = Sheets("Conductors")
Set wcd = Sheets("CDs")
Set wj = Sheets("Join")

ReDim WorkID(1 To 40)
ReDim Work(1 To 40)
ReDim ComposerName(1 To 40)
For i = 1 To 40
    WorkID(i) = ws.Range("A" & i + 1).Value
    Work(i) = ws.Range("B" & i + 1).Value
    ComposerName(i) = ws.Range("C" & i + 1).Value
Next i

ReDim ConductorID(1 To 10)
ReDim ConductorNames(1 To 10)
For i = 1 To 10
    ConductorID(i) = wcon.Range("A" & i + 1).Value
    ConductorNames(i) = wcon.Range("B" & i + 1).Value
Next i

ReDim CDWorkID(1 To 132)
ReDim CDCondID(1 To 132)
For i = 1 To 132
    CDWorkID(k) = wcd.Range("A" & i + 1).Value
    CDCondID(k) = wcd.Range("B" & i + 1).Value
Next i

For i = LBound(CDWorkID) To UBound(CDWorkID)
    wj.Range("F" & i) = CDWorkID(i)
Next i

End Sub

答案 1 :(得分:2)

Range("B" * k + 1).Value有拼写错误 - 你的意思是Range("B" & k + 1).Value。这使range提升&#34;类型&#34;错误。 消除这一点使代码运行没有错误 - 我怀疑错误消息是不正确的。

顺便说一下,还有另一个陷阱(不会导致运行时错误,至少不会导致显示的代码):
Dim i, j, k, m As Long Dim ws, wcon, wcd, wj As Worksheet
不会将i, j, k声明为整数而是声明为变体。对于ws, wcon, wcd,它们是变体而非工作表对象。