具有环的细胞的相对参考

问题描述 投票:0回答:1

我正在尝试创建一个循环,该循环写入引用其上方一系列单元格的公式。

Dim y1 As Integer
Dim x1 As Integer
Dim x2 As Integer
Dim y2 As Integer
Dim i

x1 = 5
y1 = 10
x2 = 43


  For i = 1 To 500

  Range(Cells(x2, 4)).Value = "=1-Sum(" & Range(Cells(x1, 4), Cells(y1, 4)) & ")"""
    x1 = x1 + 22
    y1 = y1 + 22
    x2 = x2 + 22
    y2 = y2 + 22

  Next

所以对于单元格D21,我想说“= 1-SUM(D5:D10)”,D43“= 1-sum(D27:D32)”等。

vba loops reference cell relative
1个回答
1
投票

范围需要两个单元格,一个开头和一个结尾(或一个字符串)。

Range(Cells(x2, 4))

应该只是

Cells(x2, 4)

Range(Cells(x1, 4), Cells(y1, 4))

返回您尝试连接到字符串的值数组。

你需要返回一个字符串的地址:

Range(Cells(x1, 4), Cells(y1, 4)).Address(0,0)

其他说明:

  • 人们应该将父表单分配给所有范围对象
  • 所有+ 22都可以使用i作为乘法器内联。
  • 引用行号时使用Long而不是Integer,因为它们可能超过Integer的允许值。

Dim y1 As Long
Dim x1 As Long
Dim x2 As Long
Dim i As Long


x1 = 5
y1 = 10
x2 = 43

With Worksheets("Sheet1") 'Change to your sheet
    For i = 1 To 500
      .Cells((i - 1) * 22 + x2, 4).Value = "=1-Sum(" & .Range(.Cells((i - 1) * 22 + x1, 4), .Cells((i - 1) * 22 + y1, 4)).Address(0,0) & ")"
    Next
End With
© www.soinside.com 2019 - 2024. All rights reserved.