2014-09-12 2 views
0

나는 모든 형식을 연속 된 형태로 반복하고 "소유자"필드에서 이름을 가져온 다음 고유 값 (반복되는 이름 없음) 만 포함하는 컬렉션을 만드는 유일한 목적을 작성했습니다.두 변형을 비교할 때 유형이 일치하지 않는 이유는 무엇입니까?

아래 코드는 현재 코드입니다.이 코드는 원하는대로 할 수있는 것으로 생각되지만 일부 예상치 못한 문제로 인해 내가 원하는 방식으로 수행 할 수 없습니다. 그래서 코드가 매우 효과적이지는 않다는 것을 깨닫는 동안 (그리고 매우 거친 코딩입니다) 나는 학습 경험을 위해서만이 길을 마무리하고 싶습니다. 이 코드 줄은 항상 형식 불일치 오류 메시지를 표시합니다. 나는 그 변수가 로컬 윈도우에 무엇인지 알기 위해 중단 선을 사용했습니다. 둘 다 동일해야하는 문자열을 포함하므로 true를 반환해야합니다. 그 비교 작업을 실제로 할 수있는 방법을 찾지 못하는 것 같습니다.

ElseIf var = o Then 

코드 (무거운 I 분명 해요 확인하기 위해 주석) :

Private Sub Command39_Click() 

    Dim intRecordCount As Integer 
    Dim rs As DAO.Recordset 
    Dim colNames As Collection 
    Set colNames = New Collection 

    Set rs = Me.RecordsetClone 

    intRecordCount = rs.RecordCount 

    DoCmd.GoToRecord , , acFirst 


    If intRecordCount > 0 Then 

     Dim thisCol As Collection 
     Set thisCol = New Collection 

     'For each record on the form 
     Do While Not rs.EOF 

      Dim str As String 
      Dim o As Variant 

      str = Me.txtOwners.Value & "" 

      'If the textbox isn't empty 
      If Len(str) > 0 Then 

       'Send the string containing names ("Bob, Cheryl, Jeff, Tim") 
       Set thisCol = SplitNames(str) 

       'Loop through all of the names found 
       For Each o In thisCol 

        Dim var As Variant 
        Dim blnFound As Boolean 

        'Loop through all names in the main collection 
        For Each var In colNames 

         'If the collection is empty simply add the first name 
         If colNames.Count = 0 Then 
          blnFound = False 

         'If the collection has items check each one to see if the name is already in the collection 
         'This line is where the problem lies, I can't find anyway to compare var to o 
         ElseIf var = o Then 
          blnFound = True 
         End If 

        Next var 

        'If the name was not found in the collection add it 
        If Not blnFound Then 
         colNames.Add (o) 
        End If 
       Next o 

      End If 

      'Go to the next record in the continuous 
      DoCmd.GoToRecord , , acNext 
      rs.MoveNext 
     Loop 

    End If 


End Sub 


'Accepts the name of the owners to be split 
Public Function SplitNames(strNames As String) As Collection 


    Dim colNames As Collection 
    Dim strThisName As String 

    Set colNames = New Collection 

    'Replaces ("Bob, Cheryl, Jeff, Tim") with ("Bob Cheryl Jeff Tim") 
    'I realize this isn't really needed simply my OCD requires I do 
    strNames = Trim(Replace(strNames, ", ", " ")) 

    'Create the collection of names 
    colNames.Add (Split(strNames, " ")) 

    'Send back the collection 
    Set SplitNames = colNames 

End Function 

업데이트 - 어떤 이유로 내가 VAR를 사용하여 VAR 문자열 때에 프로퍼티에 액세스해야 (0) 그래서 것 같다 어떻게 든 var는 자체 배열이 되었습니까?

+1

당신은 대신 모음의 사전 객체를 사용할 수 있습니다. 사전 객체는 부울 값을 반환하는'.Exists' 메소드를 가지고 있습니다. –

+0

내가 그 하하를 사용할 수있는 적어도 4 곳의 다른 장소를 알고 있기 때문에 나는 분명히 그 장면을 줄 것이다. 왜 그 비교가 효과가 없는지 알겠습니까? – Newd

+0

스플릿 함수를 사용하여 사전에 들어갈 수 있다고 생각하지 않습니까? – Newd

답변

0

다음은 필요한 작업을 수행하는 업데이트 된 코드입니다. 나는 문자열 값 (문자열 대신에 Split() 함수에 의해 만들어 짐)을 추가하고 있었다.

Private Sub Command39_Click() 

    Dim intRecordCount As Integer 
    Dim rs As DAO.Recordset 
    Dim dictNames As New Collection 

    Set rs = Me.RecordsetClone 

    intRecordCount = rs.RecordCount 

    DoCmd.GoToRecord , , acFirst 
    rs.MoveFirst 

    If intRecordCount > 0 Then 

     Dim dictTheseNames As New Collection 

     'For each record on the form 
     Do While Not rs.EOF 

      Dim str As String 
      Dim o As Variant 

      str = Me.Controls("Text27").Value & "" 

      'If the textbox isn't empty 
      If Len(str) > 0 Then 

       'Send the string containing names ("Bob, Cheryl, Jeff, Tim") 
       Set dictTheseNames = SplitNames(str) 

       'Loop through all of the names found 
       For Each o In dictTheseNames 

        Dim var As Variant 
        Dim blnFound As Boolean 
        blnFound = False 

        'Loop through all names in the main collection 
        For Each var In dictNames 

         'If the collection is empty simply add the first name 
         If dictNames.Count = 0 Then 
          dictNames.Add (o) 

         'If the collection has items check each one to see if the name is already in the collection 
         'This line is where the problem lies, I can't find anyway to compare var to o 
         ElseIf o = var Then 
          blnFound = True 
         End If 

        Next var 

        'If the name was not found in the collection add it 
        If Not blnFound Then 
         dictNames.Add (o) 
        End If 
       Next o 

      End If 

      'Go to the next record in the continuous 
      rs.MoveNext 

      If (rs.RecordCount - rs.AbsolutePosition) > 2 Then 
       DoCmd.GoToRecord , , acNext 
      End If 

     Loop 

    End If 


End Sub 


'Accepts the name of the owners to be split 
Public Function SplitNames(strNames As String) As Collection 


    Dim dictNames As New Collection 
    Dim strThisName As String 
    Dim strArray() As String 

    Set dictNames = New Collection 


    'Replaces ("Bob, Cheryl, Jeff, Tim") with ("Bob Cheryl Jeff Tim") 
    'I realize this isn't really needed simply my OCD requires I do 
    strNames = Trim(Replace(strNames, ", ", " ")) 

    'Create the array of names 
    strArray = Split(strNames, " ") 

    Dim o As Variant 
    For Each o In strArray 
     dictNames.Add (o) 
    Next o 

    'Send back the collection 
    Set SplitNames = dictNames 

End Function 
1

다음은 SplitNames 함수를 사전 개체로 수정 한 예입니다.

코드에서 elsehwere를 사용할 수있는 Exists 메서드가있는 경우 고유성을 보장하기 위해 해당 코드를 사용할 필요가 없습니다. 단순히 같은 방법으로 사용 (존재하는 경우 또는 덮어 쓰기) 새 키를 생성 할 수 있도록 그것을 생성하는 키에를 참조 :

dict(key) = value 

참고이 키의 부분을 덮어 씁니다을/값 쌍. 그러나 SplitNames 함수는 고유 한 이름의 "목록"을 작성하는 것이므로 문제가 될 것이라고 생각하지 않습니다. 예를 들어, 각 에 null 문자열을 할당하기 만하면됩니다.

나는 당신이, 고유 한 이름의 중 하나 사전을 반환 할 수 있도록이 함수에 선택적 매개 변수를 추가 또는 (사전 변환) 컬렉션. 테스트되지는 않았지만 작동해야한다고 생각합니다. 네가 그것에 문제가 있으면 알려줘.
Public Function SplitNames(strNames As String, Optional returnCollection as Boolean=False) As Object 
    'returns a Dictionary of unique names, _ 
    ' or a Collection of unique names if optional returnCollection=True 

    Dim dictNames as Object 
    Dim strThisName As Variant 
    Dim coll as Collection 
    Set dictNames = CreateObject("Scripting.Dictionary") 

    'Replaces ("Bob, Cheryl, Jeff, Tim") with ("Bob Cheryl Jeff Tim") 
    'I realize this isn't really needed simply my OCD requires I do 
    strNames = Trim(Replace(strNames, ", ", " ")) 

    'Create the collection of names 
    For Each strThisName in Split(strNames, " ") 
     dictNames(strThisName) = "" 
    Next 

    If Not returnCollection Then 
     Set SplitNames = dictNames 
    Else 
     Set coll = New Collection 
     For each strThisName in dictNames.Keys() 
      coll.Add strThisName 
     Next 
     Set SplitNames = coll 
    End If 
End Function 

그래서 난 당신과 같이 프로 시저를 줄일 수 있다고 생각 :

Private Sub Command39_Click() 

    Dim intRecordCount As Integer 
    Dim rs As DAO.Recordset 
    Dim dictNames As Object 
    Dim collNames as Collection 
    Dim str As String 
    Dim o As Variant 

    Set rs = Me.RecordsetClone 

    intRecordCount = rs.RecordCount 

    DoCmd.GoToRecord , , acFirst 
    rs.MoveFirst 

    If intRecordCount > 0 Then 

     'For each record on the form 
     Do While Not rs.EOF 
      str = Me.Controls("Text27").Value & "" 

      'If the textbox isn't empty 

      If Len(str) > 0 Then 

       'Send the string containing names ("Bob, Cheryl, Jeff, Tim") 
       Set dictNames = SplitNames(str) 

       'Alternatively, if you want to work with the Collection instead: 
       Set collNames = SplitNames(str, True) 

      End If 
     Loop 
    End If 
End Sub 
관련 문제