2014-06-16 74 views
0

我試圖選擇以下行,但它給我一個調試錯誤。我認爲,因爲實際的字符串超過了256個字符。沒有最後127:127的字符串,起作用。我怎樣才能解決這個問題?我如何選擇多行字符串

「不起作用

Range("488:488,456:456,455:455,454:454,453:453,448:448,441:441,440:440,439:439,438:438,437:437,436:436,435:435,421:421,414:414,395:395,392:392,391:391,390:390,389:389,388:388,387:387,386:386,385:385,384:384,383:383,382:382,381:381,380:380,379:379,378:378,369:369,127:127").Select 

」任職

Range("488:488,456:456,455:455,454:454,453:453,448:448,441:441,440:440,439:439,438:438,437:437,436:436,435:435,421:421,414:414,395:395,392:392,391:391,390:390,389:389,388:388,387:387,386:386,385:385,384:384,383:383,382:382,381:381,380:380,379:379,378:378,369:369").Select 




Selection.Copy 

    Sheets.Add after:=ActiveSheet 
    ActiveSheet.Paste 
    ActiveSheet.Name = "test1" 

回答

2

有更短的方式來表示你的範圍,但他們是否真正解決您的問題取決於地區最大數量你可能需要選擇。

E.g

Range("A401,A403,A405").EntireRow 

使用較小的範圍比字符串

Range("401:401,403:403,405:405") 

,但如果您需要選擇更多的行那麼最終也將失敗。作爲一種變通方法你可以聯盟在一起的兩個不同的範圍:

... = Application.Union(Range(...), Range(...)) 
1

您可以定義範圍的字符串作爲你的每一行做了,然後循環,並將其添加到選定的範圍內。

Sub RangeSelectionTest() 

    Dim selectedRange As range 
    Dim row 
    Dim rows As String 
    Dim rowArray() As String 

    'Define row selection string 
    rows = "488:488,456:456,455:455,454:454,453:453,448:448,441:441,440:440,439:439,438:438,437:437,436:436,435:435,421:421,414:414,395:395,392:392,391:391,390:390,389:389,388:388,387:387,386:386,385:385,384:384,383:383,382:382,381:381,380:380,379:379,378:378,369:369,127:127,150:150" 

    'Split to an array to loop 
    rowArray = Split(rows, ",") 

    ' Loop through all rows and add to range 
    For Each row In rowArray 
     If selectedRange Is Nothing Then 
      Set selectedRange = range(row) 
     Else 
      Set selectedRange = Union(selectedRange, range(row)) 
     End If 
    Next 

    ' Select the range 
    selectedRange.Select 

End Sub 

實際上,您可以創建一個函數,該函數接受範圍字符串並返回範圍對象。

Sub SelectMyRange() 
    Dim rows As String 
    'Define row selection string 
    rows = "488:488,456:456,455:455,454:454,453:453,448:448,441:441,440:440,439:439,438:438,437:437,436:436,435:435,421:421,414:414,395:395,392:392,391:391,390:390,389:389,388:388,387:387,386:386,385:385,384:384,383:383,382:382,381:381,380:380,379:379,378:378,369:369,127:127,150:150" 

    Dim myRange As range 
    Set myRange = RangeSelection(rows) 
    myRange.Select 
End Sub 

Function RangeSelection(rangeString As String) As range 

    Dim selectedRange As range 
    Dim row 
    Dim rowArray() As String 

    'Split to an array to loop 
    rowArray = Split(rangeString, ",") 

    ' Loop through all rows and add to range 
    For Each row In rowArray 
     If selectedRange Is Nothing Then 
      Set selectedRange = range(row) 
     Else 
      Set selectedRange = Union(selectedRange, range(row)) 
     End If 
    Next 

    ' Return the range 
    Set RangeSelection = selectedRange 

End Function 
+1

這是很棒的劇本!謝謝,我是本書的標記 – Val