2012-04-03 170 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