2016-11-18 44 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