下标超出范围

我想看看为什么我得到这个问题。

Private Sub test() Dim Row As Integer For Row = 1 To 100 'Loop through SummaryRange and ignore blanks but get document type' Dim documentTypes As String Dim myDocument As String, Column As Integer Column = 2 'First get range from Summary' Sheets("Sheet1").Active If ActiveSheet.Cells(Row, Column).Value <> "" Then documentTypes = documentTypes + "," + ActiveSheet.Cells(Row, Column).Value Sheets("Sheet12").Active ActiveSheet.Range("B17").Value = documentTypes Next Row End Sub 

我试图在不同的工作表中循环一个范围,然后获取值,然后将它们连接成一个string并输出该string。

编辑:

除去了SummaryRange,摆脱了超范围的问题,但是调出一个Object doesn't support this property or method

尝试改变:

  Sheets("Sheet1").Active 

至:

  Sheets("Sheet1").Activate 

对于以下情况也是如此:

  Sheets("Sheet12").Active 

尝试改变

 SummaryRange.Range("Row:Column").Value 

 SummaryRange.Range(Row:Column).Value 

更新:尝试以下

 Dim range As Range Dim row As Range Dim cell As Range Set range = Range("B1:B100") For Each row In range.Rows For Each cell in row.Cells 'processing code 'documentTypes = documentTypes + "," + cell.Value 'etc... Next cell Next row 

虽然bouvierr已经回答你现有的问题,我注意到你可以避免循环,更有效地做到这一点

这条线
strOut = Join(Application.Transpose(ws.Range("B1:B100")), ",")
产生由逗号分隔的B1:B100的所有值的string

由于一些值可能是空的,结果string可能看起来像这样的test,1,2,3,,,3,,afaff,,,,,,,,,,,

所以我用一个正则expression式来清理多个,

 Sub QuickGrab() Dim ws As Worksheet Dim objRegex Dim strOut As String Set ws = Sheets("Sheet1") strOut = Join(Application.Transpose(ws.Range("B1:B100")), ",") Set objRegex = CreateObject("vbscript.regexp") With objRegex .Pattern = ",{2,}" .Global = True strOut = .Replace(strOut, ",") End With MsgBox strOut End Sub