VBA如果值匹配,如何从另一个工作簿中复制相应的列值

时间:2019-01-30 03:28:38

标签: excel vba

我已经对Excel VBA进行了一些研究。但是我仍然找不到解决我问题的方法。

我使用宏的原因是因为它必须每周执行一次。宏应该做的是,当值与两个工作簿中的列A(列 项目 )匹配时,它将将未分配存量从工作簿2(列H)复制到(列) C)在工作簿1中。

练习册2
IMAGE of workbook 2

工作簿1
IMAGE of workbook 1

下面的部分代码不起作用。随意分享您自己的代码,因为我也不擅长VBA。 (如果可能,请添加评论,以便我易于理解)

  FindString = ws1.Range("A" & j) 'stock item number
  If Trim(FindString) <> "" Then ' if item number not equal to blank
    With ws3.Range("A:A") 'searches all of column A of sum up sheet
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.count), _
                       LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
         '---If intersite exists in ws3
                '---------VLOOKUP ------------

        'If (ws1.Range("H" & j).Value > ws3.Range("B" & j).Value) Then

          ' here = Rng.Row


            'ws1.Range("A" & j & ":R" & j).Copy ws4.Range("A" & lrow4)              'Copy stockworkbook range A(j) until R(j)  until paste to worksheet Output
            'lrow4 = ws4.Cells(ws4.Rows.count, "A").End(xlUp).Row + 1                 'lastrow tambah 1

          ws1.Range("H" & j).Copy ws3.Range("c" & lrow4)
          lrow4 = ws3.Cells(ws4.Rows.count, "c").End(xlUp).Row + 1

Image: No error in coding but the output is wrong

Image: Result of blank output in column C

1 个答案:

答案 0 :(得分:0)

尝试一下:

在制品 在制品:不可能参考workbook.worksheet ist 在制品

    Dim i as Integer 'will run through workbook 2
    Dim j as Integer 'will run through workbook 1

    Dim wbOne as Workbook
    Set wbOne = Workbook("WorkbookOne")
    Dim wbTwo as Workbook
    Set wbTwo = Workbook("WorkbookTwo") 'replace with correct naming

    Dim wsOne as Worksheet
    Set wsOne = Worksheets("WorksheetOne")
    Dim wsTwo as Worksheet
    Set wsTwo = Worksheets("WorksheetTwo")


    for i = 1 to 1000 'length wb1
        for j = 1 to 10000 'length wb2
            if wbTwo.wsTwo.cells(i,1).value = wbOne.wsOne.cells(j,1).value then 
                wbTwo.wsTwo.cells(i,3).value = wbOne.wsOne.cells(j,8).value
                exit for 'exit j loop because match was found
            end if
        next j
    next i

您可以动态调整工作簿的长度。如果不清楚的话,问一下。 另一个提示:您似乎有大量数据,因此双循环可能需要很长时间才能计算出来。通过将所有数据保存在数组中,然后在数组上执行double循环,可以使该程序大大更快。