[英]Excel VBA Copying range values to an Array,
我有以下代码摘录,我试图将一系列值复制到声明的数组上,但它一直给我“无法分配给数组”错误,
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)
有人可以帮忙吗? 我真的看不出这两种方法有什么问题。 :-(
==============================
我试过以下,
Dim permittedCurve(4) As Variant
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
这仍然会产生相同的“无法分配给数组”错误......为什么?
当您从工作表的单元格批量加载时,您总是会得到一个二维数组。 可以将第一列视为“行”,将第二列视为“列”。
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
考虑到与原生工作存在的问题(管理费用) 变调功能,坚持使用2-d阵列,如果你打算铲值从工作表集体来回。
可以通过更改变量声明来解决更新的问题。
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
您可以一次完成一个单元格 - 这似乎是一种缓慢的方法,但只有 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
我今天刚刚在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.