Search code examples
vbainternet-explorerweb-scraping

Unable to embed images right next to their concerning asins in a worksheet


I'm trying to create a script in vba in combination with IE to scrape image link from some webpages and embed the same right next to ASIN column in a worksheet. In column A there are list of ASINs' and in column B, I would like to embed the image like this. So, the script takes asin from column A and forms a qualified link by appeneding that asin to this base link https://www.amazon.in/dp/. This is the address of one such webpage.

Here are some asins:

B08SRFZX5Z
B08KKJQ8N7
B081RC61YN

Which forms the following links:

https://www.amazon.in/dp/B08SRFZX5Z
https://www.amazon.in/dp/B08KKJQ8N7
https://www.amazon.in/dp/B081RC61YN

I've tried with:

Sub GetImages()
    Const URL$ = "https://www.amazon.in/dp/"
    Dim IE As Object, ws As Worksheet, cel As Range
    
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set IE = CreateObject("InternetExplorer.Application")

    For Each cel In ws.Range("A2:A" & ws.Cells(Rows.count, 1).End(xlUp).Row)
        IE.Visible = False
        IE.navigate URL & cel
        While IE.Busy Or IE.readyState < 4: DoEvents: Wend
        ws.Range(cel(1, 2).Address) = IE.document.querySelector("[id='imgTagWrapperId'] > img").getAttribute("src")
    Next cel
End Sub

How to embed image right next to asin list in a worksheet?


Solution

  • Use AddPicture method insert picture using URL:

    ws.Shapes.AddPicture("image url", msoFalse, msoTrue, cel.OffSet(0,1).Left, cel.OffSet(0,1).Top, -1. -1)

    -1 indicate use the original size but you can change the width and height at your desired size.

    https://learn.microsoft.com/en-us/office/vba/api/excel.shapes.addpicture