2016-11-18 43 views
0

我在不同的工作簿中有幾個數據庫(表),並且對於每個表,需要將幾個特定列複製到一個工作表中。另外,每列應粘貼在收件人/主工作表的特定列中。由於我是新的宏,我一步一步寫我的代碼。要知道,我有代碼複製一個表的列並將其粘貼到主表中。但是,這些列正在被複制3次,與前一列相同,我不知道爲什麼。我只希望列複製一次。循環複製粘貼列複製它們多於期望的次數

以下是代碼

Dim f As Range, WB As Workbook 
Dim arrSht, Arrcol As Variant, j As Long 

arrSht = Array("a","b","c") 
Arrcol = Array(5, 6, 8) 

Set WB = Workbooks.Open(Filename:= _ 
    "C:\Users\gustavo\Documents\Minambiente\TUA\2015\CARDER\CARDER.xls") 

With Application 
    .ScreenUpdating = False 
    .DisplayAlerts = False 
End With 

For j = LBound(arrSht) To UBound(arrSht) 

    Set f = WB.Sheets(1).Cells.Find(arrSht(j), searchorder:=xlByRows, LookAt:=xlPart) 

If Not f Is Nothing Then 
    WB.Sheets(1).Range(f.Offset(1, 0), Sheets(1).Cells(Rows.Count, f.Column).End(xlUp)).Copy 
     ThisWorkbook.Sheets(1).Cells(Rows.Count, Arrcol(j)).End(xlUp).Offset(1, 0).PasteSpecial 
     Else 
     MsgBox arrSht(j) & "Header not found!" 
End If 

    With Application 
    .ScreenUpdating = False 
    .DisplayAlerts = False 
    End With 
Next j  

回答

0

我不知道結構或文件的內容。但在我看來,你的問題來自使用LookAt:= xlPart。因爲在第一次迭代期間,如果搜索範圍中的一個單元格包含「a」,則

If Not f Is Nothing Then 

被檢查。 和第二次迭代期間,如果電池中的一個包含字母「b」被選中

If Not f Is Nothing Then 

條件。 等等... 嘗試使用:

LookAt: = xlWhole. 

希望這可以幫助。

+0

謝謝!我再次檢查,這是我的新手錯誤。我已經運行了三次代碼:P –

0

對不起,我再次檢查了代碼,這是我的新手錯誤。我已經運行了三次代碼:P