2012-12-07 3 views

답변

2

이 기능이 마음에 들거나 두 가지 기능이 필요합니까? 이 같은

Function findValues(place As String, val As String, rng As Range) As Integer 
    Dim r As Range 
    findValues = 0 
    For Each r In rng 
     If InStr(r.Value2, val) > 0 Then 
      findValues = r.Row 
      If LCase(place) = "first" Then 
       Exit For 
      End If 
     End If 
    Next 
End Function 

사용 :

Dim rng As Range 
Set rng = Range("B1:B10") 
Dim i As Integer 
i = findValues("first", "B", rng) 
i = findValues("last", "B", rng) 

확인할 필요가 범위의이 시간이 걸릴 수 있습니다 얼마나 큰에 따라.

+0

내가있는 moreso 변수에 대한 행 번호를 할당하는 것을 시도하고 당신은 범위로 RNG를 정의 할 수있는 열 – KaliMa

+0

의 크기에 대한 어떤 가정을 아니에요을 모두 퍼팅 이 경우 –

+0

아, 아주 멋지다. 실제로 작동합니다. 고맙습니다! – KaliMa

1

다른 방법이 있습니다.

Sub FindFirstLast() 

    Dim vaValues As Variant 
    Dim vaFilter As Variant 
    Dim lFirst As Long 
    Dim lLast As Long 

    Const sFIND As String = "B" 

    With Application.WorksheetFunction 
     'Get a 1-d array from a column 
     vaValues = .Transpose(Sheet1.Range("A1:A10").Value) 

     'Use match to get the first instance 
     lFirst = .Match(sFIND, vaValues, False) 

     'Filter on the values 
     vaFilter = Filter(vaValues, sFIND) 

     'Assumes they're all together 
     lLast = lFirst + UBound(vaFilter) 
    End With 

    Debug.Print lFirst, lLast 

End Sub 
1

저는 몇 가지 응용 프로그램에서 Kevin Pope의 방법을 사용해 왔지만 때때로 원하지 않는 것들이 포함되어있는 것으로 나타났습니다. 내 경험과 해결책을 나눌 줄 알았다.

Mouser EPM1270GT144I5 
Mouser EPM1270GT144I5 
Mouser GRM32DR71E106K 
Mouser GRM32DR71E106K 
TTI  GRM32DR71E106KA12L 
Avnet GS816273CC-250I 
Avnet GS816273CC-250I 

이 찾고 있던 : GRM32DR71E106K

그것은 내가 검색 한 두 개의 동일한로 시작하는 세 번째를 반환

최근에 나는 이런 식으로 뭔가가 있다면 실현 끈.

정확한 일치 검색을 위해 적응해야했습니다. 수정본은 매우 쉬웠습니다.

Public Function findValues(Val As String, Rng As Range, Optional place As Integer) As Integer 
     Dim R As Range 
     findValues = 0 
     For Each R In Rng 
      If StrComp(R.Value2, Val) = 0 Then 
    '  If InStr(R.Value2, Val) > 0 Then 
       findValues = R.Row 
       If place = 1 Then 
        Exit For 
       End If 
      End If 
     Next 
    End Function 

누군가가 유용하다고 생각합니다.

9

VBA에서는 여전히 다양한 내장 Excel 기능에 액세스 할 수 있습니다. 예 (데이터를 가정 할 열 1 인) :

첫 번째 B 찾기 ...
Columns(1).Find(What:="B", LookAt:=xlWhole, MatchCase:=False).Row 'Returns 5

마지막 B를 찾기 ...
Columns(1).Find(What:="B", LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False).Row 'Returns 7

B가 발견되지 않는 경우, 오류가 리턴됩니다. B가 없으면 오류 처리를 사용하여 0을 반환함으로써이 기능을 활용할 수 있습니다. 에서 : ("B B") ... 함께

Sub DoTest() 
    Dim RowFirst As Integer, _ 
     RowLast As Integer 
    On Error GoTo ErrorHandler 
    RowFirst = Columns(1).Find(What:="B", LookAt:=xlWhole, SearchDirection:=xlNext, MatchCase:=False).Row 
    RowLast = Columns(1).Find(What:="B", LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False).Row 
    Exit Sub 
ErrorHandler: 
    RowFirst = 0 
    RowLast = 0 
End Sub 
+0

이것은 VBA의 기능을 사용하기 때문에 개발자가 중복 코드를 작성하지 않아도되므로 실제로 가장 좋은 대답입니다. –

관련 문제