vba - 迭代收集

时间:2017-06-18 15:40:48

标签: excel vba excel-vba collections

我想将已关闭工作簿的某些列复制粘贴到我的活动工作簿中。 我的列是separeted,所以我想通过循环而不是Collection变量。

这里是我的代码(编辑)

Option Explicit

Sub CopyDataFromClosedWbk()

    'copy data from closed workbook to active workbook
    Dim colonne As Collection
    Dim col As Variant
    Dim xlApp As Application
    Dim xlBook As Workbook
    Dim Sh As Object

    Set colonne = New Collection

    colonne.Add "A:B", "A1"
    colonne.Add "E:F", "G1"
    colonne.Add "N", "I1"
    colonne.Add "P", "F1"


    Set xlApp = CreateObject("Excel.Application")


    'Path source workbook
    Set xlBook = xlApp.Workbooks.Open("C:\Users\Amira AYADI\Desktop\Stage\Automatisation\Base Case_BDD CAPACITAIRE_ENVOYE_V2 2017_2023_24042017.xlsx")
    xlBook.Sheets("DATA").Range("A1:CJ374810").AutoFilter
    xlBook.Sheets("DATA").Range("BD1").Select
    xlBook.Sheets("DATA").Range("$A$1:$CJ$374810").AutoFilter Field:=56, Criteria1:="CMR"

    For Each col In colonne

        xlBook.Sheets("DATA").Range(col).Copy
        xlApp.DisplayAlerts = False
        Debug.Print col
        Set xlBook = Nothing
        Set xlApp = Nothing
        Set xlBook = ActiveWorkbook
        Set Sh = xlBook.Sheets("Calcul")
        'Sh.Activate
        Range(colonne.Item(col)).Select
        Sh.paste


    Next col

    xlBook.Close
    xlApp.Quit


End Sub

但这不起作用,有几个错误:

首先

Range(colonne.Item(col)).Select

不要使用“col”,而是使用索引我猜。那么如何迭代Key的值?

第二次,当我像那样重新训练col 1时(试一试):

Range(colonne.Item(1)).Select

我有91错误:对象变量或未设置块。

除此之外,我还有一个弹出窗口,说明工作簿“source.xlsx”已准备好进行修改。我该怎么办呢?

你有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

Option Explicit

Sub CopyDataFromClosedWbk()

    Dim xlApp As Application
    Dim xlBook As Workbook
    Dim sht As Worksheet, sht2 As Worksheet

    Set sht2 = ThisWorkbook.Sheets("Calcul")
    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Open("C:\Users\User\Desktop\source.xlsx") 'Adjust
    Set sht = xlBook.Worksheets("DATA")
    xlApp.DisplayAlerts = False

    sht.Range("A:CJ").AutoFilter Field:=56, Criteria1:="CMR"
    sht.Range("A:B").Copy: sht2.Range("A1").PasteSpecial xlPasteValues
    sht.Range("E:F").Copy: sht2.Range("G1").PasteSpecial xlPasteValues
    sht.Range("N:N").Copy: sht2.Range("I1").PasteSpecial xlPasteValues
    sht.Range("P:P").Copy: sht2.Range("F1").PasteSpecial xlPasteValues

    xlBook.Close
    xlApp.Quit
End Sub

我不知道是否有任何理由使用集合/字典来保存列,但这样更容易。