宏将数据从一本书拉到另一本书

时间:2015-02-06 00:34:54

标签: excel excel-vba vba

当我运行宏时,会出现提示符"编译错误:类型不匹配" 而且我不知道Application.index是否正确。您认为宏的问题是什么?谢谢。

Sub IndexMatch()    
    Application.ScreenUpdating = False

    Dim A As Workbook
    Dim B As Workbook

    Dim Aa As Worksheet
    Dim Bb As Worksheet

    Dim SearchThis As Range
    Dim LookAtE As Range
    Dim LookAtG As Range
    Dim LookAtQ As Range

    Set A = ThisWorkbook
    Set B = "Tables.xlsm"
    Set Aa = A.Sheets("Sheet24")
    Set Bb = B.Sheets("Sheet1")
    Set SearchThis = Aa.Range("A2")
    Set LookAtE = Bb.Range("E")
    Set LookAtG = Bb.Range("G")
    Set LookAtQ = Bb.Range("Q")

    Workbooks.Open ("C:\Users\admin\Documents\Tables.xlsm")
            ThisWorkbook.Activate

    Aa.Range("A4").Value = Application.Index(LookAtG, Match(SearchThis, LookAtE))
    Aa.Range("A5").Value = Application.Index(LookAtQ, Match(SearchThis, LookAtE))

  Workbooks("Tables.xlsm").Close SaveChanges:=True
 Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:1)

尝试设置如下:

Set B = Workbooks("Tables.xlsm")

如果另一个表也打开,这应该有效。


如果没有打开,请尝试:

Set B = Workbooks.Open("C:\...\Tables.xlsm")

答案 1 :(得分:0)

Sub IndexMatch()
    Application.ScreenUpdating = False

    Workbooks.Open ("C:\Users\admin\Documents\Tables.xlsm")
            ThisWorkbook.Activate

    Dim A As Workbook
    Dim B As Workbook

    Dim Aa As Worksheet
    Dim Bb As Worksheet

    Dim SearchThis As Range
    Dim LookAtE As Range
    Dim LookAtG As Range
    Dim LookAtQ As Range

    Set A = Workbooks("PT9.xlsm")
    Set B = Workbooks("Tables.xlsm")
    Set Aa = A.Worksheets("Sheet2")
    Set Bb = B.Worksheets("Documents")
    Set SearchThis = Aa.Range("A2")
    Set LookAtE = Bb.Range("E:E")
    Set LookAtG = Bb.Range("G:G")
    Set LookAtQ = Bb.Range("Q:Q")


    Aa.Range("A4").Value = Application.Index(LookAtG, WorksheetFunction.Match(SearchThis, LookAtE))
    Aa.Range("A5").Value = Application.Index(LookAtQ, WorksheetFunction.Match(SearchThis, LookAtE))


  Workbooks("Tables.xlsm").Close SaveChanges:=True
 Application.ScreenUpdating = True
End Sub