gpt4 book ai didi

excel - 对单列中的每个奇数行求和 VBA

转载 作者:行者123 更新时间:2023-12-02 21:20:54 24 4
gpt4 key购买 nike

我有一个代码,可以在 Excel 填充中搜索单词距离,获取旁边单元格的值,将其粘贴到新单元格中,然后将所有单元格相加。这很好用,但我现在需要找到一种方法来仅对偶数行号进行求和。那有意义吗?

Sub Distance_Check()

Dim DistanceCheck As String

Dim DistanceNumber As String

Dim DistanceSum As String

Dim DistanceTotal As String

DistanceCheck = MsgBox("Would you like to check the distance?", vbYesNo)

If DistanceCheck = vbYes Then
If IsArray(fname) Then Workbooks.OpenText fname(1)

i = 1
findStr = "Distance"
Set foundCel = Range("A:A").Find(what:=findStr)
If Not foundCel Is Nothing Then
firstAddress = foundCel.Address
Do
Range("J" & i).Value = foundCel.Offset(0, 1).Value
Set foundCel = Range("A:A").FindNext(foundCel)
i = i + 1
Loop While Not foundCel Is Nothing And foundCel.Address <> firstAddress
End If
Set wkbSourceBook = ActiveWorkbook

DistanceNumber = i - 2

DistanceSum = WorksheetFunction.Sum(Range(Cells(2, 15), (Cells(DistanceNumber + 1, 15))))
DistanceTotal = DistanceSum / DistanceNumber

If DistanceNumber = Cells(2, 12) Then
MsgBox ("No error found wihin distance")
Else
MsgBox ("Error found with distance")
End If
Else
End If
Call Save_Data
End Sub

你的方法是在

上使用 for 循环吗?
cells(DistanceNumber(j,+1) 

其中j = 0, j = j +2 ,直到 j > DistanceNumber

这行得通吗?如果是这样,你会怎么做?

谢谢

最佳答案

以所需增量单步执行循环的快速方法是使用 Mod operator它将两个数字相除并返回任何余数(例如 7 mod 2 = 1,因为两个 6 适合 7,剩下 1)。

您可以使用通过 Find 方法识别的范围的 row 属性,并且由于您想跳 2,因此模数应该为零:

If foundcel.Row Mod 2 = 0 Then Range("J" & i).value = foundcel.Offset(0, 1).Value

也就是说,如果使用这样的 For 循环,则有一种“内置”方法可以单步执行循环

For x = 2 to 10 Step 2
' Do stuff
Next x

您还可以使用此方法后退,例如

For x = 100 to 0 Step -10
' Do stuff backwards!
Next x

关于excel - 对单列中的每个奇数行求和 VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47698522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com