VBA运行时错误1004带两位数的范围

时间:2016-12-19 20:32:50

标签: excel vba excel-vba range runtime-error

我的目的是选择连续的每个其他单元格。我的代码(我确信必须有更好的方法来完成这个,但我猜是一步一步):

Range("C" & row & ":C" & row + 1 & ", E" & row & ":E" & row + 1 & ", G" & row & ":G" & row + 1 & ", I" & row & ":I" & row + 1 & ", K" & row & ":K" & row + 1 & ", M" & row & ":M" & row + 1 & ", O" & row & ":O" & row + 1 & ", Q" & row & ":Q" & row + 1 & ", S" & row & ":S" & row + 1 & ", U" & row & ":U" & row + 1 & ", W" & row & ":W" & row + 1 & ", Y" & row & ":Y" & row + 1 & ", AA" & row & ":AA" & row + 1 & ", AC" & row & ":AC" & row + 1 & ", AE" & row & ":AE" & row + 1 & ", AG" & row & ":AG" & row + 1 & ", AI" & row & ":AI" & row + 1 & ", AK" & row & ":AK" & row + 1 & ", AM" & row & ":AM" & row + 1 & ", AO" & row & ":AO" & row + 1 & ", AQ" & row & ":AQ" & row + 1 & ", AS" & row & ":AS" & row + 1 & ", AU" & row & ":AU" & row + 1 & ", AW" & row & ":AW" & row + 1 & ", AY" & row & ":AY" & row + 1 & ", BA" & row & ":BA" & row + 1).Select

我递增2以突出显示每隔一行。当row超过10时,它会返回错误(对象'_Global'的方法'范围'失败)。我无法通过Google找到任何答案。似乎不是一个常见的问题。我真的很神秘,为什么它只适用于单位数行。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

这可能更容易编码读|调试。

Dim ws as Worksheet
Set ws = Worksheets("mySheet") 'change as needed

Dim x as Integer
For x = 3 to 53 Step 2 'loop from C to BA skipping 1 column in between

   Dim rngEveryOther as Range
   If rngEveryOther is Nothing
       Set rngEveryOther = ws.Range(ws.Cells(i,x),ws.Cells(i+1,x))
   Else
       Set rngEveryOther = Union(rngEveryOther, ws.Range(ws.Cells(i,x),ws.Cells(i+1,x)))
   End If

Next

rngEveryOther.Select

Union语句将单元格连接到现有范围(如果代码中不明显)。