2012-03-01 2 views
0

특정 열의 모든 연속 행을 반환하는 작업이 있습니다. 그들은 모두 데이터를 연속적으로 가지며 첫 번째 빈 행은 데이터의 끝을 알릴 것입니다. 나는 이것을 사용하여 컬럼을 찾고이를 내 범위로 전달하지만 구문 오류가 계속 발생합니다.Excel VBA를 사용하여 열만 알려져있는 경우 셀 범위를 반복하는 방법?

Dim Col 
Dim found As Boolean 
Dim cellRange As Range 

    found = Cells.Find(What:="My_Search_Text", After:=ActiveCell, LookIn:=xlValues, _ 
     LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
     MatchCase:=False, SearchFormat:=False).Activate 

    'Take that column as the range. 
    If (found) Then 
     Col = ActiveCell.Column 
     cellRange = ActiveSheet.Range(Col, ActiveSheet.Range(Col).End(xlDown)).Select 

목표는 여기 마지막 줄은 전혀 작동하지 않는 일이다 그러나 나는 루프 부분에 아니에요, 그들을 통해 세포와 루프의 정확한 범위를 얻을 수 있습니다.

이 마지막 줄의 올바른 구문은 무엇이며 수행하려는 작업을 수행하는 더 나은 방법이 있습니까?

그런데
Set found = Cells.Find(What:="My_Search_Text", After:=ActiveCell, LookIn:=xlValues, _ 
     LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
     MatchCase:=False, SearchFormat:=False) 

, 당신은 할당 할 수 없습니다 및이 방법을 사용하면 VBA 개체를 사용하는 경우

+0

'ActiveCell.Column'은 범위가 아닌 열 번호를 반환합니다. – Excellll

+0

그게 내가 범위를 얻을 필요가 있다고 생각하는 것입니다, 먼저 열을 찾으십시오. –

+0

'Find()'는 범위를 반환하므로'found '선언은 "As Range"이어야합니다. 그리고 Find() 끝에서 ".Activate"를 제거하십시오. 그렇다면'Col = found.Column'을 사용하십시오. –

답변

4

나는 상황의 선택과 테스트 한 다음을 시도해보십시오

그런 다음 사용하여 범위를 설정합니다.

내가 변경 한 사항에 대한 메모를 포함했지만 명확하지 않은 부분이 있으면 다시 질문을드립니다.

Option Explicit 
Sub FindRange() 

    Dim RangeStart As Range 
    Dim RangeEndPlusOne As Range 
    Dim RangeEntire As Range 

    ' Better to explicitly identify the sheet being searched 
    With Sheets("Source") 
    ' Do not attempt to activate the target cell. Instead get it as a range. 
    ' Are you sure about "LookAt:=xlPart"? "LookAt:=xlWhole" might be better 
    ' I have explicitly started the search from cell A1 rather than the current 
    ' position of the cursor. 
    Set RangeStart = .Cells.Find(What:="My_Search_Text", After:=.Range("A1"), _ 
           LookIn:=xlValues, LookAt:=xlPart, _ 
           SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
           MatchCase:=False, SearchFormat:=False) 

    If RangeStart Is Nothing Then 
     ' My "My_Search_Text" not found 
    Else 
     ' If the cell below RangeStart is empty, End(xlDown) will jump to 
     ' the bottom of the column or the next cell in the column with a value. 
     ' Search down the column for an empty cell 
     Set RangeEndPlusOne = .Columns(RangeStart.Column).Find(What:="", _ 
          After:=RangeStart, _ 
          LookIn:=xlValues, LookAt:=xlWhole, _ 
          SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
          MatchCase:=False, SearchFormat:=False) 
     ' I ought to test for not found but I assume there is a blank cell below 
     ' RangeStart 

     Set RangeEntire = .Range(RangeStart, RangeEndPlusOne.Offset(-1, 0)) 

     Debug.Print "Start " & RangeStart.Address 
     Debug.Print "End+1 " & RangeEndPlusOne.Address 
     Debug.Print "Entire " & RangeEntire.Address 
    End If 

    End With 

End Sub 
+3

좋은 것. 시간을내어 완전한 답을 얻었습니다. 'If ​​Not'를 사용하여'else do do not do do''를 피할 수 있습니다 : – JMax

+0

당신은 맞지만'Not X Is Nothing'과 같은 부울 표현으로 내 머리가 아파요. 나는 빈'Then' 블록을 선호한다. 그러나 : (1) 실제 코드에서 대상 텍스트가 발견되지 않으면 몇 가지 작업을 기대하고 (2) 내 정신적 제한이없는 제임스에게이 사실을 지적하는 것이 좋습니다. –

+0

12 년 동안 Excel VBA 코드에서 벗어난 Java 개발자로서 VBA 제한 사항이 있습니다. 훌륭한 답변과 인내심에 감사드립니다. –

2

, 당신은 변수를 할당 할 때, 당신의 첫 번째 문이어야 키워드 Set를 사용해야합니다 Activate. 그래서 저는 성명서의 마지막 부분에서 그것을 삭제했습니다.

+0

이것은 작동하지 않습니다. 난 그냥 범위를 얻을 수 있도록 열 번호를 얻기 위해 찾기를 사용하고 있습니다. 어떻게이 변수를 정의 할 수 있습니까? –

+0

@JamesDrinkard : 토니의 대답을보세요. 그는 전체 작업 솔루션을 제공합니다 – JMax

2

마지막 행을 가져 오는 방법에 대해 어떻습니까?

LastRow = SheetToCheck.Cells(ActiveCell.Row, ActiveCell.Column).End(xlDown).Row 

이것은 나누기/공백 셀 앞에있는 마지막 행을 반환합니다.

Set cellRange = SheetToCheck.Range(SheetToCheck.Cells(ActiveCell.Row, ActiveCell.Column), SheetToCheck.Cells(LastRow, ActiveCell.Column)) 
+0

나는 당신이 길을 잃어 버리면 문제가 발생할 수 있으므로 ActiveCell/ActiveSheet/Selection을 사용하는 것을 싫어합니다. 셀/시트를 직접 참조하는 것이 좋습니다. 현재 선택된 셀을 사용하는 경우 Set myCell = ActiveCell로 지정하십시오. 선택이 중간 프로세스로 변경되면 gum up되지 않습니다. – Gaffi

관련 문제