基本上我正在尝试写一个循环 - 第一次迭代时会有
srcT = Worksheets("I").Range("B1").Value
srcC = Worksheets("I").Range("B2").Value
trgT = Worksheets("I").Range("B3").Value
trgC = Worksheets("I").Range("B4").Value
然后第二次迭代
srcT = Worksheets("I").Range("B5").Value
srcC = Worksheets("I").Range("B6").Value
trgT = Worksheets("I").Range("B7").Value
trgC = Worksheets("I").Range("B8").Value
然后第3次迭代
srcT = Worksheets("I").Range("B9").Value
srcC = Worksheets("I").Range("B10").Value
trgT = Worksheets("I").Range("B11").Value
trgC = Worksheets("I").Range("B12").Value
并继续使用此模式,直到在B列中遇到空白单元格。
答案 0 :(得分:1)
编写循环的方法有很多种;这是一个:
Option Explicit
Sub Test()
Dim srcT As String
Dim srcC As String
Dim trgT As String
Dim trgC As String
Dim counter As Long
Const ADD_FACTOR = 4
Const WORKSHEET_NAME = "I"
Const COLUMN_TO_USE = "B"
Dim blankFound As Boolean
blankFound = False
counter = 1
Do
srcT = Worksheets(WORKSHEET_NAME).Range(COLUMN_TO_USE & counter).Value
srcC = Worksheets(WORKSHEET_NAME).Range(COLUMN_TO_USE & counter + 1).Value
trgT = Worksheets(WORKSHEET_NAME).Range(COLUMN_TO_USE & counter + 2).Value
trgC = Worksheets(WORKSHEET_NAME).Range(COLUMN_TO_USE & counter + 3).Value
blankFound = srcT = "" Or srcC = "" Or trgT = "" Or trgC = ""
counter = counter + ADD_FACTOR
Loop While blankFound = False
End Sub
注意每个变量都有声明,并且使用常量以便于阅读。
答案 1 :(得分:1)
Sub LoopExample()
Dim i as Integer
With Worksheets("I")
For i = 1 to 3
srcT = .Cells(i, 2).Value
srcC = .Cells(i + 1, 2).Value
trgT = .Cells(i + 2, 2).Value
trgC = .Cells(i + 3, 2).Value
Next i
End With
End Sub
请注意在选择对象时使用With
来优化VBA性能。
下次请注意:
[编辑]正如@Readify在评论中指出的那样,我忘了回答“最后一行”。这是一个线程(readify做了一个非常明确的答案顺便说一下),可以帮助你:Getting the actual usedrange