2017-12-14 3 views
0

3 개의 구분 된 범위를 통해 루프를 만들고 각 변수에 값을 넣으려면 키 생성 된 콜렉션 코드 (thanks @ Mat'sMug!)를 수정하려고합니다. 첫 번째 키 입력 수집은 잘 작동하지만 치수 또는 Dim(x to y) 또는 ReDim(x to y)y와 redimensioning 때 라인 ReDim ccAddresses(0 To ccRecipients.Count - 1)VBA : 다중 키 모음 다시 드릴 = 오류 9 '아래 첨자 범위를 벗어났습니다'?

Private Sub AddUniqueItemToCollectionzz(ByVal value As String, ByVal items As Collection) 
    On Error Resume Next 
    items.Add value, Key:=value 
    On Error GoTo 0 
End Sub 

Sub Sampletest() 
    Dim toRecipients As Collection 
    Set toRecipients = New Collection 
    Dim ccRecipients As Collection 
    Set ccRecipients = New Collection 
    Dim cc2Recipients As Collection 
    Set cc2Recipients = New Collection 


    '===============Copy primary email addresses============= 
    With toRecipients 
     For Each cell In Range("H1:H350") 
      If cell.value Like "*@*.*" Then 
       AddUniqueItemToCollectionzz cell, toRecipients 
      End If 
     Next 
    End With 

    ReDim toAddresses(0 To toRecipients.Count - 1) 

    Dim toAddress As Variant, toItem As Long 
    For Each toAddress In toRecipients 
     toAddresses(toItem) = CStr(toAddress) 
     toItem = toItem + 1 
    Next 

    Dim sendToPrim As String 
    sendToPrim = Join(toAddresses, ";") 

    '=====================Copy cc email addresses====================== 
    With ccRecipients 
     For Each cell In Range("J1:J350") 
      If cell.value Like "*@*.**" Then 
       AddUniqueItemToCollectionzz cell, ccRecipients 
      End If 
     Next 
    End With 

    ReDim ccAddresses(0 To ccRecipients.Count - 1) 

    Dim ccAddress As Variant, ccItem As Long 
    For Each ccAddress In ccRecipients 
     ccAddresses(ccItem) = CStr(ccAddress) 
     ccItem = ccItem + 1 
    Next 

    Dim sendToCC As String 
    sendToCC = Join(ccAddresses, ";") 

    '====================Copy cc2 email addresses================ 
    With cc2Recipients 
     For Each cell In Range("A1:a350") 
      If cell.value Like "*.uSA.TACO*" Then 
       AddUniqueItemToCollectionzz cell, cc2Recipients 
      End If 
     Next 
    End With 

    ReDim cc2Addresses(0 To cc2Recipients.Count - 1) 

    Dim cc2Address As Variant, cc2Item As Long 
    For Each ccAddress In cc2Recipients 
     cc2Addresses(cc2Item) = CStr(cc2Address) 
     cc2Item = cc2Item + 1 
    Next 

    Dim sendToCC2 As String 
    sendToCC2 = Join(cc2Addresses, ";") 
+0

'cc2Recipients'는 호출 될 때 무엇입니까? 나는 당신이 그것을 무엇으로 설정했는지, 또는 컬렉션에 먼저 추가하는 것을 보지 못합니다. 그 줄 앞에'debug.print cc2Recipients.count'를두면, 에러가 발생하거나'0'을 리턴해야합니다. – BruceWayne

+0

절차가 시작되고 끝나는 곳을 말하기는 어렵습니다. 코드 [여기] (http://rubberduckvba.com/indentation) (면책 조항 : 해당 웹 사이트를 소유하고 있음)를 붙이고 "들여 쓰기"를 눌러보십시오. 버튼 =) –

+0

@ BruceWayne Solved. 위의 업데이트를 참조하십시오. – Gurrito

답변

2

에서 오류를 뱉어 두 번째는 (은 두 번째지나 도착하면 나는 세 번째를 추측하고있어) x 이상이어야합니다. 따라서 ReDim ccAddresses(0 To ccRecipients.Count - 1) 문 앞에 다음 줄을 추가하여 코드를 확인하십시오.

Debug.Assert ccRecipients.Count >0 
+0

감사합니다. 나는 그 문제를 해결했다. 감사! – Gurrito