You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过循环/计数器在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 6 with For counter = 2 To 6 Step 2 — the Step 2 tells VBA to jump 2 rows each time instead of 1.
  • Remove the unnecessary Select calls 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 2 modifier makes the counter variable 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 messy Select and ActiveChart calls — this makes your code run faster and avoids bugs that can happen if the active cell/chart changes unexpectedly.

内容的提问来源于stack exchange,提问作者amea6995

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:22:52