2016-07-15 188 views
1

語境:新來VBAExcel的VBA:循環通過在Sheet1兩列,查找特定的名稱,粘貼行與匹配值到Sheet2

任務:我在Worksheet1聯繫人列表中包含的列:姓氏,名字,電子郵件,電話號碼等等。我在Worksheet2第二聯繫人列表(格式完全一樣),其中包含大約在Worksheet1聯繫人列表但更新的聯繫人信息(電子郵件,電話號碼等),發現1000名500。我試着寫代碼,找出其名稱在兩個工作表,併爲那些名字,從Worksheet2(更新信息)複製電子郵件,電話號碼等,並將其粘貼到在Worksheet2相應的位置。

代碼:這是我到目前爲止所。這是行不通的。

Sub UpdateContacts() 

Dim Reference As String 
Dim Range As Range 
Dim ContactList As Worksheet 
Dim UpdatedContacts As Worksheet 

ContactList = ActiveWorkbook.Sheets("Contact List") 
UpdatedContacts = ActiveWorkbook.Sheets("Updated Contacts") 

Reference = ContactList.Range("B5", "C5").Value 

j = 5 

For i = 5 To UpdatedContacts.Cells(Rows.Count, 1).End(xlUp).Row 

     If UpdatedContacts.Range(Cells(i, 2), Cells(i, 3)).Value = Reference Then 
      UpdatedContacts.Range(Cells(i, 4), Cells(i, 17)).Copy _ 
      Destination:=ContactList.Range(Cells(j, 4), Cells(j, 17)) 
      j = j + 1 
     End If 
    Next i 
End Sub 

任何幫助,非常感謝!

感謝

+0

這可以在不VBA和工作表公式來完成。你對這個解決方案好嗎?這是一次性的事情,還是需要一遍又一遍的處理? –

+0

如何在沒有VBA的情況下執行?我希望不得不不斷更新某些聯繫人。 – Coles

+0

如果你有一個新的聯繫人片場,你可以放置在'sheet2'爲模板,然後有一個3片式一切基於保存在Sheet1中所有的名字,然後有公式來查找名稱Sheet 2中,如果他們存在從那裏拉數據,否則從sheet1拉它。然後粘貼表單3作爲整個當前列表中的表單1的值。一旦它成立,更新它基本上是2個數據。很快。 –

回答

1

下面是一些小的改進,如Option Explicit,在任何時候都完全合格的引用,Option Compare Text忽略大寫字母比較名稱時,Trim忽略可能的開頭或結尾空格的工作方案,並創建另一外環做所有的名字比較上shtContactList

Option Explicit 
Option Compare Text 

Sub UpdateContacts() 

Dim ws As Worksheet 
Dim rngCell As Range 
Dim i As Long, j As Long 
Dim strReference As String 
Dim shtContactList As Worksheet 
Dim shtUpdatedContacts As Worksheet 

For Each ws In ThisWorkbook.Worksheets 
    Select Case ws.Name 
     Case "Contact List" 
      Set shtContactList = ws 
     Case "Updated Contacts" 
      Set shtUpdatedContacts = ws 
     Case Else 
      Debug.Print ws.Name 
    End Select 
Next ws 
If shtContactList Is Nothing Or shtUpdatedContacts Is Nothing Then 
    MsgBox "One or more required sheet(s) were not found." & Chr(10) & "Aborting..." 
    Exit Sub 
End If 

For j = 5 To shtContactList.Cells(shtContactList.Rows.Count, "A").End(xlUp).Row 
    strReference = Trim(shtContactList.Cells(j, 2).Value2) & ", " & Trim(shtContactList.Cells(j, 3).Value2) 
    For i = 5 To shtUpdatedContacts.Cells(shtUpdatedContacts.Rows.Count, 1).End(xlUp).Row 
     If Trim(shtUpdatedContacts.Cells(i, 2).Value2) & ", " & Trim(shtUpdatedContacts.Cells(i, 3).Value2) = strReference Then 
      shtUpdatedContacts.Range(shtUpdatedContacts.Cells(i, 4), shtUpdatedContacts.Cells(i, 17)).Copy _ 
       Destination:=shtContactList.Range(shtContactList.Cells(j, 4), shtContactList.Cells(j, 17)) 
      j = j + 1 
     End If 
    Next i 
Next j 

End Sub 

如果代碼運行緩慢,你可能要考慮使用數組:(1)把整個片shtUpdatedContacts到一個數組以及表shtContactList和(2)然後在那裏進行搜索/比較。 (3)最後,將更新數組粘貼回表shtContactList

+0

謝謝拉爾夫,我很感激幫助。我跑這個代碼,但沒有發生任何事。我會繼續審查。 – Coles

相關問題