excel 序列中的交换函数同一行中的单元格

taor4pac  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(82)

代码(与SumOffset1)完美地工作,并给出了正确的结果,在单元格(5,2)运行的功能,它从单元格(3,3)开始。你能帮助我如何修改函数,以便在单元格(5,3)和从单元格(3,4)开始的函数等得到正确的结果。

Sub commulative()
   
    Dim i As Integer
    For i = 0 To 5
        If Cells(4, 2) <= SumOffset1(i) Then
            Cells(5, 2) = (i - 1) * 5 + (Cells(4, 2) - SumOffset1(i - 1)) / (Cells(3, i + 2) / 5)    
            Exit For
        End If     
    Next i
 
End Sub

Function SumOffset1(iteration As Integer) As Double
    Dim sum As Double   
    Dim j As Integer   
    For j = 1 To iteration
        sum = sum + Cells(3, 2).Offset(0, j)
    Next j
   
    SumOffset1 = sum
End Function

使用上面的代码,函数只总结了(3,2)和(3,3)等单元格。我想有一些东西,如下所示,但它不起作用:

Sub commulative()
   
    Dim i As Integer 
    For i = 0 To 5
        If Cells(4, k) <= SumOffset1(i) Then       
            Cells(5, k)= (i - 1) * 5 + (Cells(4, k) - SumOffset1(i - 1)) / (Cells(3, i + k) / 5)                                 
            Exit For
        End If  
    Next i 

End Sub

Function SumOffset1(iteration As Integer) As Double
    Dim sum As Double
    Dim j As Integer
   
    For j = 1 To iteration   
        sum = sum + Cells(3, k).Offset(0, j)       
    Next j
   
    SumOffset1 = sum
End Function
mspsb9vt

mspsb9vt1#

我不想修改代码的其他部分(Integer很少有用,Long是整数的常用类型,SumOffset1可能应该内联,等等),因为我不明白它做了什么,为什么这是好的。
但是,如果当前代码对您有效,并且您只想对k = 2,3,4 ...(你没有提到,但我猜直到找到一个空单元格),然后你可以像这样修改它(我用注解“Added”标记了两个新行):

Sub commulative()
   
    Dim i As Integer
    For i = 0 To 5
        Dim k As Long: For k = 2 To ActiveSheet.Cells(4, 2).End(xlToRight).Column ' Added
            If Cells(4, k) <= SumOffset1(i) Then
                Cells(5, k) = (i - 1) * 5 + (Cells(4, k) - SumOffset1(i - 1)) / (Cells(3, i + k) / 5)
                Exit For
            End If
        Next ' Added
    Next i

End Sub

Function SumOffset1(iteration As Integer) As Double
    Dim sum As Double
    Dim j As Integer
   
    For j = 1 To iteration
        sum = sum + Cells(3, k).Offset(0, j)
    Next j
   
    SumOffset1 = sum
End Function

相关问题