2012-04-03 136 views
2

我想知道为什么我得到这个问题。下标超出范围

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 

我通过一系列努力环在不同的工作表,然后让值,然后将它们连接起来成一个字符串,并输出字符串。

编辑:

删除SummaryRange,摆脱出一系列问题,但带来了一个Object doesn't support this property or method

+0

VBA的哪行产生错误? 'SummaryRange.Range(“Row:Column”)。Value对我来说看起来并不合适,您应该实际指定Row和Column的值。 – mellamokb 2012-04-03 23:02:51

+0

行列本质上,我和j,我编辑它忽略SummaryRange不应该那样。由于我得到的更改: – Anicho 2012-04-03 23:11:51

+0

对象不支持此方法或属性 – Anicho 2012-04-03 23:12:58

回答

1

尝试改变:

Sheets("Sheet1").Active 

要:

Sheets("Sheet1").Activate 

同为是正确的:

Sheets("Sheet12").Active 
+0

作为一个附注,我也强烈建议你使用它们的对象名称来引用表格,而不是: 表格(“Sheet12”) 简单地写: Sheet12 您可以通过在VBA编辑器中编辑工作表的“(Name)”属性来更改工作表的对象名称。 – bouvierr 2012-04-04 00:36:38

+0

用于识别问题的+1 – brettdj 2012-04-04 01:10:02

1

尝试改变

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 
+0

Nadaa它应该是'ActiveSheet.Cells(Row,Column).Value'。好点。虽然我仍然遇到相同的问题:( – Anicho 2012-04-03 23:08:02

+0

请看我的更新回答 – BluesRockAddict 2012-04-03 23:33:14

1

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

此行
strOut = Join(Application.Transpose(ws.Range("B1:B100")), ",")
产生从B1中的所有值的字符串:B100由逗号

分离作为一些值可能是空的结果字符串可能看起来像这样的事情 test,1,2,3,,,3,,afaff,,,,,,,,,,,

所以我用正则表达式来清理多个,成一个单一的'

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 
+0

感谢这给我一个捆绑包:D – Anicho 2012-04-05 08:28:00