Excel VBA将范围值复制到数组,

时间:2016-02-14 23:47:25

标签: arrays excel-vba vba excel

我已经获得了以下代码摘录,我尝试将一系列值复制到声明的数组中,并且不断向我提供“无法分配给数组&#” 39;错误',

Javascript.js

我也试过这个,但给了我同样的错误..

Dim permittedCurve(0 To 7000) As Variant

permittedCurve = activeWorkbook.Worksheets("Origin").Range("AB6:AB7006").value

有人可以帮忙吗?我不认为这两种方法都有任何问题。 : - (

=============================

更新

我已尝试过以下内容,

Dim permittedCurve(7000) As Variant

permittedCurve = application.transpose(activeWorkbook.Worksheets("Origin").Range("AB6:AB7006").value)

这仍然可以推动同样的#34;不能分配给阵列"错误......为什么?

3 个答案:

答案 0 :(得分:1)

从工作表的单元格批量加载时,始终会获得一个二维数组。第一个排名可以被视为“行”,第二个排名可以被视为“列”。

dim permittedCurve As Variant
'the following is the same as redim permittedCurve(1 to 3, 1 to 6)
permittedCurve = Range("A1:F3").Value2
debug.print lbound(permittedCurve, 1) & ":" & ubound(permittedCurve, 1)
debug.print lbound(permittedCurve, 2) & ":" & ubound(permittedCurve, 2)
'results from the Immediate window:
1:3
1:6

考虑到使用本地TRANSPOSE function的问题(和开销),如果您计划从工作表 en masse 来回挖掘值,请坚持使用2-D数组。 / p>

可以通过更改变量声明来解决更新的问题。

Dim permittedCurve As Variant  '<~~ just a variant, not specifically a variant array with 5 elements
Dim indicationCurve(4) As Variant

indicationCurve(0) = 1
indicationCurve(1) = 10
indicationCurve(2) = 100
indicationCurve(3) = 1000
indicationCurve(4) = 10000

'Copying the curves
permittedCurve = indicationCurve
'now it's a variant array with 5 elements

答案 1 :(得分:0)

你可以一次完成一个单元格 - 这似乎是一个缓慢的方法,但只有7000个单元格,它应该在几分之一秒内运行

Dim rngTarget As Range
Set rngTarget = ActiveWorkbook.Worksheets("Origin").Range("AB6:AB7006")

Dim permittedCurve(0 To 7000) As Variant

Dim i As Long
For i = 0 To UBound(permittedCurve)
    permittedCurve(i) = rngTarget.Cells(i + 1, 1)
Next i

编辑1:了解新事物 - 尝试:

Dim permittedCurve() As Variant
ReDim permittedCurve(1 To 7001)
permittedCurve = Application.Transpose(Range("AB6:AB7006"))

For i = 1 To UBound(permittedCurve)
    Debug.Print permittedCurve(i)
Next

答案 2 :(得分:0)

我今天在Excel 365中遇到了类似的错误(这就是我找到此线程的原因),它看起来像是由于VBA对象有些奇怪。似乎只要将工作表对象与范围分开定义,并且工作表处于活动状态,就可以接受将范围转换为变量的方法。

Dim wkb As Workbook:    Set wkb = Workbooks("WorkbookName.xls")
Dim wks As Worksheet:   Set wks = wkb.Worksheets("WorksheetName")
Dim strRange As String: strRange = "A1:Z1"

' Setting a range for a worksheet that's not active gives an error
' Don't know why. Just need to do it.
wks.Activate
Dim rng As Range:       Set rng = wks.Range(strRange)

Dim varRange() As Variant
varRange = rng                                             ' Works
varRange = rng.Value                                       ' Works
varRange = wks.Range(strRange)                             ' Works
varRange = wkb.Worksheets("WorksheetName").Range(strRange) ' Does not work