我在学校学习VBA,在一些基础知识上有困难。
我用随机整数通过A1通过D1填充单元格。
我想对它们进行求和,并将解决方案放在E1中。
Sub Add_Four_Numbers()
Dim CBArray(3) As Double
For i = 1 To 4
Cells(i, 4) = gerry(Cells(i, 1), Cells(i, 2), Cells(i, 3), Cells(i, 4))
Next i
End Function我一直得到:
编译错误错误变量数
我试图修复数组的维数,但没有成功。
有人能告诉我吗?
谢谢。
发布于 2016-10-06 07:01:40
不确定学校作业是什么,但是有几种方法可以将单元格A1-D1中的值和起来,并在单元格E1中得到结果。
在下面的代码中,有3种方法对它们进行总结。
(不知道为什么要使用数组,这是分配的一部分吗?)
Option Explicit
Sub Add_Four_Numbers()
Dim Sht As Worksheet
Dim i As Long
' always set your cells to a sheet varibale >> modify "Sheet1" to your Sheet's name
Set Sht = ThisWorkbook.Sheets("Sheet1")
' option 1: using WorksheetFunction SUM and your pre-defined Range
With Sht
.Range("E1").Value = WorksheetFunction.Sum(.Range("A1:D1"))
End With
' option 2: using WorksheetFunction SUM and Cells reference inside
With Sht
.Range("E1").Value = WorksheetFunction.Sum(.Cells(1, 1), .Cells(1, 2), .Cells(1, 3), .Cells(1, 4))
End With
' option 3: using a For loop
With Sht
.Range("E1").Value = 0
For i = 1 To 4
.Range("E1").Value = .Range("E1").Value + .Cells(1, i)
Next i
End With
End Subhttps://stackoverflow.com/questions/39887186
复制相似问题