创建可获取单元格值的vba循环

时间:2019-01-22 03:06:47

标签: excel vba loops

我正在尝试为vba创建一个宏,该宏将获取在单元格1-1000的A列中输入的值,然后将这些值插入到函数中。

不是将1000个不同的值定义为:

x1 = Worksheets("Sheet1").Range("A1").Value

x2 = Worksheets("Sheet1").Range("A2").Value

x3 = Worksheets("Sheet1").Range("A3").Value

...等等

然后将它们插入我的函数中

Dim dy As Integer, fx As Integer dy = Range("B2").Value - Range("B1").Value fx= dy*(x1+x2+x3....)

我是否可以创建一个从单元格A1到A1000的do循环,以获取它们各自的值并将其插入函数中?这是我到目前为止的内容,但是我不确定如何获取在单元格中输入的值。

xi = 1
Do
xi = 1 + xi
If xi = 1000 Then Exit Do
Count = Count + 1

Loop

2 个答案:

答案 0 :(得分:0)

'create a zero-based array o9f the values in A1:A1000
dim x as variant
with Worksheets("Sheet1")
    x = application.transpose(.range("A1:A1000").value)
end with

'sum all of x
dim i as long, sumX as double
for i = lbound(x) to ubound(x)
    sumX = sumX + x(i)
next i

'another way to sum A1:A1000
with Worksheets("Sheet1")
    sumX = application.sum(.range("A1:A1000").value)
end with

'your function
Dim dy As long, fx As long
with Worksheets("Sheet1")
    dy = .Range("B2").Value - .Range("B1").Value
end with
fx = dy * sumX 

答案 1 :(得分:0)

以下查询适用于您。该代码可灵活获取列“ A”中的行数。无需硬编码上限值

Dim dy As Integer, fx As Integer, iCellSum As Integer
Sub Main()
    iRowCount = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
    iCellSum = 0
    For i = 1 To iRowCount
        iCellSum = iCellSum + Sheets("Sheet1").Cells(i, 1)
    Next

    dy = Range("B2").Value - Range("B1").Value

    fx = dy * iCellSum

End Sub