我的任务听起来非常简单,但它给了我一些麻烦。
我需要做的只是简单地选择从3到305的所有奇数行(因此同时选择行3
)。
在对行5
和Range("3:3,5:5").Select
进行多项选择时录制宏,我看到生成的代码如下:
Dim strRange As String, j As Integer
strRange = "3:3,"
For j = 5 To 303 Step 2
strRange = strRange & j & ":" & j & ","
Next j
strRange = strRange + "305:305"
从上面开始,我写了以下内容:
strRange
以上Debug.Print strRange
>>> 3:3,5:5,7:7,9:9,11:11,13:13,15:15,17:17,19:19,21:21,23:23,25:25,27:27,29:29,31:31,33:33,35:35,37:37,39:39,41:41,43:43,45:45,47:47,49:49,51:51,53:53,55:55,57:57,59:59,61:61,63:63,65:65,67:67,69:69,71:71,73:73,75:75,77:77,79:79,81:81,83:83,85:85,87:87,89:89,91:91,93:93,95:95,97:97,99:99,101:101,103:103,105:105,107:107,109:109,111:111,113:113,115:115,117:117,119:119,121:121,123:123,125:125,127:127,129:129,131:131,133:133,135:135,137:137,139:139,141:141,143:143,145:145,147:147,149:149,151:151,153:153,155:155,157:157,159:159,161:161,163:163,165:165,167:167,169:169,171:171,173:173,175:175,177:177,179:179,181:181,183:183,185:185,187:187,189:189,191:191,193:193,195:195,197:197,199:199,201:201,203:203,205:205,207:207,209:209,211:211,213:213,215:215,217:217,219:219,221:221,223:223,225:225,227:227,229:229,231:231,233:233,235:235,237:237,239:239,241:241,243:243,245:245,247:247,249:249,251:251,253:253,255:255,257:257,259:259,261:261,263:263,265:265,267:267,269:269,271:271,273:273,275:275,277:277,279:279,281:281,283:283,285:285,287:287,289:289,291:291,293:293,295:295,297:297,299:299,301:301,303:303,305:305
将导致以下结果:
Range(strRange).Select '<-- Note: workbook and worksheet are correctly referenced
......看起来很正确。但是,当我尝试这样做时:
Run-time error 1004: Method 'Range' of object '_Global' failed.
...我得到Range
为什么会这样?我可以传递给我在网上找不到的{{1}}类的字符串的最大长度是多少?如果是这样,我将如何进行多重选择?
答案 0 :(得分:2)
尝试一下:
Sub OddPicker()
Dim rng As Range, i As Long
For i = 3 To 305 Step 2
If rng Is Nothing Then
Set rng = Cells(i, 1)
Else
Set rng = Union(rng, Cells(i, 1))
End If
Next i
rng.EntireRow.Select
End Sub
我找不到 Range()的字符串限制;我看了看这里:
Excel Specifications and Limits
修改#1:强>
我跑了这个:
Sub flskdjfs()
Dim strRange As String, j As Integer
strRange = "3:3,"
Dim r As Range
On Error GoTo whatis
For j = 5 To 303 Step 2
strRange = strRange & j & ":" & j & ","
Set r = Range(Mid(strRange, 1, Len(strRange) - 1))
Next j
strRange = strRange + "305:305"
whatis:
MsgBox j & vbCrLf & Len(strRange)
End Sub
得到了这个MsgBox结果:
所以我假设在256个字符之后 Range()变得松散。