如何通过循环/计数器在VBA中每次下移2行而非1行
Fixing the Loop to Move 2 Rows at a Time in Your VBA Code
Got it, let's get this sorted for you! The key change you need is adjusting your loop's step value so it increments by 2 instead of the default 1. Plus, I'll clean up the code a bit to avoid relying on Select (which is usually slower and more error-prone than directly referencing objects).
Here's what to modify:
- Replace your original loop line
For counter = 2 To 6withFor counter = 2 To 6 Step 2— theStep 2tells VBA to jump 2 rows each time instead of 1. - Remove the unnecessary
Selectcalls to make the code more efficient and reliable.
Modified Full Code:
Sub Languages() Dim counter As Integer Dim targetChart As Chart ' Loop from row 2 to 6, stepping by 2 each iteration For counter = 2 To 6 Step 2 ' Add the chart directly to a variable (no need to select) Set targetChart = ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Chart ' Apply your saved chart template targetChart.ApplyChartTemplate "C:\Users\arboari\AppData\Roaming\Microsoft\Templates\Charts\1Language.crtx" ' Set source data, now jumping 2 rows each loop targetChart.SetSourceData Source:=Range("'Master Sheet'!$B$" & counter & ":$F$" & counter) ' Note: I completed the range reference assuming you want row B-F for each counter value; adjust if needed! Next counter End Sub
Quick Breakdown:
- The
Step 2modifier makes thecountervariable increment by 2 every loop (so it goes 2 → 4 → 6), which is exactly what you need to shift 2 rows each time. - By assigning the chart to a variable (
targetChart), we skip the messySelectandActiveChartcalls — this makes your code run faster and avoids bugs that can happen if the active cell/chart changes unexpectedly.
内容的提问来源于stack exchange,提问作者amea6995
相关产品推荐
相关产品推荐

