我有一个代码,可以在excel填充中搜索单词distance,获取旁边单元格的值,将其粘贴到新单元格中,然后对所有单元格求和。哪个效果很好,但我现在需要找到一种方法来只计算行数。那有意义吗?
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
,
那会有用吗?如果是这样你会怎么做呢?
谢谢
答案 0 :(得分:1)
以所需增量逐步循环的快速方法是使用Mod operator除以两个数字并返回任何余数(例如7 mod 2 = 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