【问题标题】:Why does VBA For Next Loop calculation incorrect?{VBA}为什么 VBA For Next Loop 计算不正确?{VBA}
【发布时间】:2021-05-12 12:00:08
【问题描述】:

我是 VBA 新手 - 尝试使用 VBA 进行简单计算,但无法使其正常工作。任何帮助将不胜感激。 基本上我有一行,结果应该等于之前的结果+当前根据单元格

这就是我的意思

A B C D
(1)Row 1 1 2 3 4
(2)Result 1 (1+2) (1+2)+3 ((1+2)+3)+4

我一直用for Next,但无法生成我想看到的结果,第一次输出是正确的,但是第一次计算后,所有正在进行的计算都不正确

Sub DeltaAllocationToCRSSum()
   Range("A2").Value = 1  ' Set starting value for the first cell in the result roll  
   Dim Column1 As Integer  
   Dim Column2 As Integer  
   For Column1 = 1 to 4     
      For Column2 = 2 To 5   
         Cells(2,Column2) = Cells(2,Column1)+Cells(1,Column2) 'meaning B2 = A2 + B1 for the first calculation  
      Next Column2    
   Next Column1

所以这段代码总能得到第一次计算的正确结果,但连续的结果总是错误的。有人知道是什么问题吗?抱歉,这个问题可能很基础,但我自己无法弄清楚....谢谢您的帮助

【问题讨论】:

  • 看来你不需要两个for循环。将column2 替换为column1 +1

标签: excel vba vba6


【解决方案1】:

你只需要一个for循环,试试这个

Sub DeltaAllocationToCRSSum()
Range("A2").Value = 1  ' Set starting value for the first cell in the result roll
Dim Column1  As Integer
 
For Column1 = 1 To 4
 
Cells(2, Column1 + 1) = Cells(2, Column1) + Cells(1, Column1 + 1) 'meaning B2 = A2 + B1 for the first calculation
 
Next Column1
End Sub

【讨论】:

    【解决方案2】:

    试试这个


    for i = 2 to usedrange.columns.count
       if i =2 then 
          cells(2,i) = cells(2,i).offset(-1,0)   ' column a
       else
          cells(2,i)= cells(2,1).offset(0,-1)+ cells(1,i)
       end if
    next i
    

    【讨论】:

      猜你喜欢
      • 2015-11-02
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2017-03-22
      • 2020-01-31
      • 2015-05-15
      相关资源
      最近更新 更多