2013-10-29 94 views
1

我對VBA很陌生,並且很難理解一些語法。設置變量結束的VBA範圍

例如,我有一個範圍從a3:c13,我想將它設置爲一個變量,所以我可以稍後將它作爲表數組傳遞給vlookup。但是,範圍由用戶輸入的大小來定義。它將始終在A3開始,它將始終包括列A:C,但我不知道它會走多遠。在這種情況下,我認爲我將它設置爲:

With range("a3") 
    table_array = range(.cells(0,0), .End(xlDown).End(xlToRight)).Select 
End With 

但是,這似乎並不奏效。我得到一個運行時錯誤:

Run-time Error '1004': Method '_Default' of object 'Range' failed.

回答

1

假設的cols A,B和C具有相同的行數:

Sub Macro1() 
    Set r = Range("A3") 
    Set table_array = Range(r, r.End(xlDown)).Resize(, 3) 
End Sub 
+0

真棒,快速,簡潔! – idalsin

0

你可以在柱A中的最後一行:C,然後構造你的範圍?

Sub Sample() 
    Dim ws As Worksheet 
    Dim LastRow As Long 
    Dim Rng As Range 

    '~~> Change this to the relevant sheet 
    Set ws = ThisWorkbook.Sheets("Sheet1") 

    With ws 
     If Application.WorksheetFunction.CountA(.Cells) <> 0 Then 
      LastRow = .Range("A:C").Find(What:="*", _ 
          After:=.Range("A1"), _ 
          Lookat:=xlPart, _ 
          LookIn:=xlFormulas, _ 
          SearchOrder:=xlByRows, _ 
          SearchDirection:=xlPrevious, _ 
          MatchCase:=False).Row 
     Else 
      LastRow = 1 
     End If 

     If Not LastRow < 3 Then 
      Set Rng = .Range("A3:C" & LastRow) 

      Debug.Print Rng.Address 
     Else 
      MsgBox "No Data found beyond A3" 
     End If 
    End With 
End Sub