Changing worksheet while using VLookup causes problems

后端 未结 2 1688
终归单人心
终归单人心 2021-01-23 14:32

I want to import two values in total from two different worksheets. I have the worksheets Site1 and Site2. From these I want to import the values corre

相关标签:
2条回答
  • 2021-01-23 14:55

    I have finally found a solution for this problem. I post this as an answer as I've been under the impression that VLookup or Application.Match along with the switch in worksheets caused the problems, and after googling this issue found out that some other code authors has believed the same.

    For me the solution was simply to Close the workbook used before changing the worksheet. In my code I have added the minor adjustments to the code.

      Set currentWb = ActiveWorkbook
      Set openWb = Workbooks.Open(filepath & Path) ' It imports the correct file
      Set openWs = openWb.Sheets("Site1")
      currentWb.Sheets("Sheet1").Cells(2,3).Value = Application.WorksheetFunction.VLookup("Product1", openWs.Range("A1:R30"), Application.Match("Cost", openWs.Range("A1:R1")))
      openWb.Close saveChanges:=False    ' Added this line
      Set openWs = openWb.Sheets("Site2")
      currentWb.Sheets("Sheet1").Cells(3,3).Value = Application.WorksheetFunction.VLookup("Product2", openWs.Range("A1:R30"), Application.Match("Cost", openWs.Range("A1:R1")))
      openWb.Cloe saveChanges:=False     'And this one 
    

    Hopefully this can be of any help to anyone else! I sure had to google quite some time before realizing I was looking in the wrong place.

    (And I'd like to thank @PaaquaGrant for investing so much time in this topic, and being a very nice person to talk to).

    0 讨论(0)
  • 2021-01-23 15:05

    Your VLOOKUP range is a single Column, instead of a multi-column range. This will always fail.

    As suggested in some of the comments, you also need to adjust all instances of current.wb to currentwb.

    0 讨论(0)
提交回复
热议问题