2017-08-09 108 views
0

我有一个Excel文件,其中列A和列B中的信息。由于这些列可能会有所不同,因此我希望使用函数补偿,以便我可以在一行中打印公式时间作为数组而不是循环遍历每个单元格的公式(数据集包含近1百万个数据点)。Excel VBA补偿函数

My data is as follow:

我的代码实际上是工作,我想这是我唯一无法弄清楚如何打印代码范围(D1:D5)的方式。结果现在打印在范围(D1:H1)中。任何人都熟悉如何在for语句中使用此偏移量?

Sub checkOffset() 

Dim example As Range 
Dim sht As Worksheet 
Dim LastRow As Long 

Set sht = ThisWorkbook.Worksheets("Sheet1") 
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 

Set example = Range("A1:A1") 

For i = 1 To LastRow 
    example.Offset(0, i + 2).Formula = "=SUM(A" & i & ":B" & i & ")" 
Next i 

End Sub 

回答

2

使用Offset(Row, Column),你想与行的增量(i -1),3列到右侧(从“A”列列“d”)

尝试下面的修改后的代码,以抵消:

输出在一个步骤式中,而不循环,于整个范围的
Set example = Range("A1") 

For i = 1 To LastRow 
    example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")" 
Next i 
1
  1. 你并不需要使用VBA这一点。只需在单元格D1中输入= sum(A1:B1),然后在fill it down中输入。

  2. 如果你还是要用VBA,使用此:

    Sub checkOffset() 
    Dim example As Range 
    Dim sht As Worksheet 
    Dim LastRow As Long 
    
    Set sht = ThisWorkbook.Worksheets("Sheet1") 
    LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 
    
    Set example = Range("A1:A1") 
    
    For i = 1 To LastRow 
        example.Offset(i - 1, 3).Formula = "=SUM(A" & i & ":B" & i & ")" 
    Next i 
    
    End Sub 
    

的方式offset作品是行偏移,列偏移。您希望列始终固定在3的右侧。

+0

是的,我明白,但因为它最终会在一个较大的工具,我建立使用我想用VBA来计算的一切。 – Tox

2

的一种方式,是使用R1C1表示法:

编辑:代码修改为PR operly资格工作表引用

Option Explicit 
Sub checkOffset() 

Dim example As Range 
Dim sht As Worksheet 
Dim LastRow As Long 

Set sht = ThisWorkbook.Worksheets("Sheet1") 

With sht 
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
    Set example = .Range(.Cells(1, 1), .Cells(LastRow, 1)) 
End With 

example.Offset(columnoffset:=3).FormulaR1C1 = "=sum(rc[-3],rc[-2])" 

End Sub