2016-05-03 44 views
1

對於很多人來說,這可能很容易,但我是VBA新手; 以下是我的代碼將多個Excel文件值添加到一個主表。雖然我這樣做,我想更新關鍵值的值。通過查找匹配鍵值來更新值

Sub tekSheetMerging() 
Dim masterSheet As Worksheet 

Set masterSheet = sheets("KoMKo") 

'Variable to save the used Range of the master sheet 
Dim usedRangeMaster As Integer 

    Dim ws As Worksheet 

    'loop through each worksheet in current workbook 
    For Each ws In Worksheets 

    'If sheetname contains "data" (UCase casts the Name to upper case letters) 
    If InStr(1, UCase(ws.Name), "DATA", vbTextCompare) > 0 Then 

     'calculate the used range of the master sheet 
     usedRangeMaster = masterSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1 

     'Variable to save the used Range of the sub sheet 
     Dim usedRangeSub As Integer 

     'calculate the used range of the sub sheet 
     usedRangeSub = ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row 

     'copy relevant range from the subsheet 
     ws.Range("C1:C" & usedRangeSub).Copy 

     'paste the copied range after the used range in column a 
     masterSheet.Range("A" & usedRangeMaster).PasteSpecial 
    End If 
    Next ws 

    End Sub 

所以,現在我有一個Excel表,其中包含列A中的鍵值和該行中其他列中的其他值。當我找到一個鍵是重複的鍵值之前添加的,我想刪除該單元格及其完整的行。通過這樣做,我想更新關於它們的關鍵值的值。如果我要添加另一個鍵,它應該留在列表中,儘管沒有問題。

我該怎麼做?

+1

上述代碼是否正常工作或者您是否遇到錯誤?如果是這樣,請給我們錯誤代碼/消息,並在哪一行發生錯誤。如果代碼運行沒有錯誤,那麼請詳細說明(1)代碼的當前結果,以及(2)上述代碼的預期結果(以及它的不同之處)。目前我只在你的代碼中看到'.Copy'和'.PasteSpecial',我想知道你希望如何實現你正在討論的'.Delete'。 – Ralph

回答

0

首先通過子工作表(資源)中的按鍵並將它們逐一與主工具中的按鍵進行比較會更好。任何比賽都應該從主控中刪除。然後,將全部數據從子工作表複製到主工作表中。

因此,我的這行代碼前雲:

'copy relevant range from the subsheet 
ws.Range("C1:C" & usedRangeSub).Copy 

與你替換我的變量:

With mastersheet 
    for i = firstrow to lastrow 'first and lastrow of data in subsheet 
     set f = .Range("A:A").Find(ws.Range("A" & i).Value, _ 
       LookIn:=xlValues, LookAt:=xlWhole) 
     If Not f is Nothing then 
      .Range("A" & f.Row).EntireRow.Delete 
     End If 
    next i 
end with 

不要忘了在此之後更新usedRangeMaster,因爲它會縮短因刪除。然後複製粘貼你的數據。

注意:此代碼假定您的密鑰是唯一的,並且您將永遠不會在主服務器中出現重複項(如果主服務器僅通過此代碼寫入,將會出現這種情況)。這就是爲什麼它只搜索一次主人。

編輯:我看到freakfeuer已經提供了一些鏈接?無論如何,讓我知道它是否有效。

+0

它適用於您,請接受它作爲答案。謝謝! – Sun