2016-07-13 4 views
0

문구가이 질문에 다소 이상하다는 것을 알았지 만 필자는 비교적 코딩에 익숙하지 않아 내 문제를 단어에 넣는 방법을 완전히 알지 못했습니다. 한 시트의 데이터 열을 반복하고 해당 열의 각 셀을 다른 시트의 지정된 행에서 검색하는 검색 용어로 사용하려고합니다. 내가 상단에있는 "F = a.Cells"에 대한 올바른 구문을 사용하고 있는지 나는 루프가 특정 셀 대신 현재있는 셀을 참조 할 이후명시 적으로 정의되지 않은 셀의 데이터 참조

Sub Test1() 
n = 0 
' n is the counter for the number of times that the search term will appear 

Dim sn As String 
For Each a In Worksheets("Sheet1").range("A5:A34").Value 
f = a.Cells 
sn = range(a).Value 
' each sn is equal to the contents of the cell "a", which will be the serial number of the tooling 


For Each c In Worksheets("RunsheetTest").range("A3:R3") 
' Defines c as a range with cells A3 to R3? 


If InStr(c.Cells, sn) > 0 Then 
n = n + 1 
Else 
n = n 
End If 
' If the serial number is found in one of the cells, add 1 to n and move on to the next. 

Next c 

MsgBox "Searching for " & sn 
range(a).Value = n 
Next a 
' I'm also getting an error here, saying "for loop not initialized", however I thought I initialized it above. 

End Sub 

나의 가장 큰 문제는,과 왜 컴파일러에서 내 루프에 오류가 발생하는지. VBA에서 중첩 루프를 실행할 수 있습니까? 또한, 내 의견 중 일부가 실제로 일어나고있는 것에 대해 완전히 정확하지 않은 경우 알려 주시기 바랍니다.

미리 감사드립니다.

+0

"f"란 무엇입니까? 변수 이름으로 무엇을하려고하는지 이해하기가 어렵습니다. – RGA

+0

VBA에서 범위를 제대로 참조하는 방법과 For Each 루프가 작동하는 방법을 연구하는 것이 좋습니다. 귀하의 일반적인 구조는 (코드 설정 방법과 같이) 건전하지만 구문/방법은 모두 꺼져 있습니다. – RGA

+0

저는 @RGA와 계약을 맺었습니다. 'a','c','f'는 변수를 설명하는 이름이 아니므로 결국 혼란 스러울 것입니다. :) 개인적으로 각 변수는 데이터 형식에 대한 3 글자 약어로 시작합니다. 예를 들어 일련 번호 변수의 경우 문자열 인'strSN'이거나 범위가 아니기 때문에'a' 대신'rngSearchTerm'이됩니다. 검색하고자하는 값이 포함되어 있습니다. – Tim

답변

0

이 시도 : 당신이 range(a) 또는 range(c)에 의해를 참조하지 않도록

Sub Test1() 
    Dim n As Integer 
    Dim a As Range 
    Dim c As Range 
    Dim sn As String 

    n = 0 
    ' n is the counter for the number of times that the search term will appear 

    For Each a In Worksheets("Sheet1").Range("A5:A34") 
     'f = a.Cells 
     sn = a.Value 
     ' each sn is equal to the contents of the cell "a", which will be the serial number of the tooling 

     For Each c In Worksheets("RunsheetTest").Range("A3:R3") 
      ' Defines c as a range with cells A3 to R3? 
      If InStr(1, c.Value, sn, vbTextCompare) > 0 Then 
       n = n + 1 
      Else 
       n = n 
      End If 
      ' If the serial number is found in one of the cells, add 1 to n and move on to the next. 
     Next 

     MsgBox "Searching for " & sn 
     a.Value = n 
    Next 
    ' I'm also getting an error here, saying "for loop not initialized", however I thought I initialized it above. 

End Sub 

ac는, 범위입니다. 또한 Next (Next a이 아님)을 사용하십시오.

+0

먼저 각 작업에 대해 그렇게할까요? "a"가 범위라고하지만 값을 반복하고 있습니까? – RGA

+1

@RGA 좋은 캐치! 실제로 코드를 테스트하지 않았고 방금 OP 코드의 실수를 수정했습니다. 나는 그것을 편집 할 것이다. – Tim

+0

@Tim - 나는 OP에 'if'의'else' 부분이 중복된다는 것을 메모하기를 원했습니다. 일단 코드가 어떻게 바뀌 었는지 이해하면 제거 될 수 있습니다. –

0

또 다른 질문 - VBA는 중첩 루프를 지원하지만 기본 제공 Range.Find() 메서드를 사용하는 것이 좋습니다. 아래 예 및 내 설명을 참조하십시오.

Sub Test1() 

    Dim n As Long 
    n = 0 ' n is the counter for the number of times that the search term will appear 

    Dim sn As String 
    Dim c As Range 
    Dim a As Range 

    '' removing ".Value" at the end -- you need to loop through a range 
    For Each a In Worksheets("Sheet1").Range("A5:A34") 
     '' here "a" is already a range object that contains one cell so all you need is: 
     n = 0 '' reset the counter for new serial number 
     sn = a 

     '' to search for a value it is better to use special .Find function on a range, not a loop 
     With Worksheets("RunsheetTest").Range("A3:R3") 

      Set c = .Find(sn, LookIn:=xlValues) 
      If Not c Is Nothing Then 
       '' you get here only if something is found, otherwise counter will be 0 -- i.e. nothing found 
       firstAddress = c.Address 
       Do 
        n = n + 1 
        Set c = .FindNext(c) 
       Loop While Not c Is Nothing And c.Address <> firstAddress 
      End If 

     End With 

     MsgBox "Searching for " & sn & " and found it " & n & " times." 

    Next a 

End Sub