大家好我有一个问题,用户可能会输入2个不同的x坐标和y坐标然后我必须在两个单一维数组中传输它们我的代码是这样但有一些错误(数组最大值= 150个值) :
Dim X as range
dim Y as range
cell as variant
ArrX( 1 to 150) as double
ArrY(1 to 150) as double
i as integer
Xcells as integer
Ycells as integer
Set X = Application.InputBox(prompt:=" Enter X coordinates", Type:=8)
Set Y= Application.InputBox(prompt:=" Enter Y coordinates",Type:=8)
这里我试图计算单元格以找到rane的实际大小并将它们分配给另一个变量但是我失败了
Xcells = X.Rows.Count
Ycells=Y.Rows.Count
i=0
for each cell in X
cell.value=arrX(i)
i=i+1
next cell
for each cell in Y
i=0
cell.value=arrY(i)
i=i+1
next cell
它总是在cell.value中抛出错误
谢谢
答案 0 :(得分:0)
您的数组的大小来自1 To 150
,这意味着1-150是有效索引。从1开始i
,它应该可以正常工作。
i = 1
For Each cell In X
cell.value = ArrX(i)
i = i + 1
Next cell
i = 1
For Each cell In Y
cell.value = ArrY(i)
i = i + 1
Next cell
但是,您没有处理X或Y中的单元格数量高于150的情况。我会动态地将数组标注为X和Y中的单元格数。
Dim ArrX() As Double
Dim ArrY() As Double
Dim i As Integer
Dim Xcells As Integer
Dim Ycells As Integer
Set X = Application.InputBox(prompt:=" Enter X coordinates", Type:=8)
Set Y = Application.InputBox(prompt:=" Enter Y coordinates", Type:=8)
Redim ArrX(X.cells.count)
Redim ArrY(Y.cells.count)
现在数组正好是你需要它们的大小。如果你这样做,也应该使用i=0
。
答案 1 :(得分:0)
为什么要烦扰循环,当你可以让Excel完成所有的工作,并且非常快:
Public Sub Test()
Dim arrx() As Variant, arry() As Variant
Dim rx As Range, ry As Range, i As Integer
Set rx = Application.InputBox(prompt:=" Enter X coordinates", Type:=8)
Set ry = Application.InputBox(prompt:=" Enter Y coordinates", Type:=8)
ReDim arrx(1 To rx.Rows.Count), arry(1 To ry.Rows.Count)
' Fill array with values
For i = 1 To rx.Rows.Count
arrx(i) = i - 1
arry(i) = 4 * Rnd() - 2 * Rnd() + 1
Next i
' Export values into worksheet
rx.Value = WorksheetFunction.Transpose(arrx)
ry.Value = WorksheetFunction.Transpose(arry)
End Sub