Insert picture from a webpageURL into excel using macros

cjain_560

New Member
Joined
Mar 10, 2021
Messages
10
Office Version
  1. 365
Platform
  1. Windows
  2. MacOS
HI guys, I hope somebody can help me here. I'm using Windows 10, Microsoft office 365.

1) I have many webpage URL with me in Column A. Using VBA, I want to extract an image from one webpage URL and put it in the next respective column. (Please note, it is a webpage URL, EX:
Chicco 6 Feeding Bottle Steriliser | White | Warmers & Sterilisers
From this URL, I want to extract the first image which is on display and put it in the second column of my excel sheet.

I'm using this VBA Code, but all it does is get the logo from the site and puts it in the second column. Please note: All my references are in place and code is working, its just I'm not getting the image on display.
VBA Code:
Option Explicit

Public Sub InsertPicturesFromWeb()
    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim imgElements As IHTMLElementCollection
    Dim imgElement As HTMLImg
    Dim aElement As HTMLAnchorElement
    Dim N As Integer, I As Integer
    Dim Url As String, Url2 As String
    Dim LastRow As Long
    Dim M, sImageSearchString
    
    LastRow = Range("A" & Rows.Count).End(xlUp).Row
    
    For I = 1 To LastRow
        Url = "https://www.babyshopstores.com/ae/en/p/" & Cells(I, 1)
        Set IE = New InternetExplorer
        
        With IE
            .Visible = True
            .Navigate Url
            
            Do Until .readyState = 4: DoEvents: Loop
                Set HTMLdoc = .document
                
                Set imgElements = HTMLdoc.getElementsByTagName("IMG")
                
                N = 1
                For Each imgElement In imgElements
                    If InStr(imgElement.src, sImageSearchString) Then
                        If imgElement.ParentNode.nodeName = "A" Then
                            Set aElement = imgElement.ParentNode
                            
                            Url2 = imgElement.src
                            N = N + 1
                        End If
                    End If
                Next
                
                Call GetShapeFromWeb(Url2, Cells(I, 2))
                
                IE.Quit
                Set IE = Nothing
            End With
        Next I
End Sub

Sub GetShapeFromWeb(strShpUrl As String, rngTarget As Range)
   With rngTarget.Parent
      .Pictures.Insert strShpUrl
      .Shapes(.Shapes.Count).Left = rngTarget.Left
      .Shapes(.Shapes.Count).Top = rngTarget.Top
   End With
End Sub
 

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
HI guys, I hope somebody can help me here. I'm using Windows 10, Microsoft office 365.

1) I have many webpage URL with me in Column A. Using VBA, I want to extract an image from one webpage URL and put it in the next respective column. (Please note, it is a webpage URL, EX:
Chicco 6 Feeding Bottle Steriliser | White | Warmers & Sterilisers
From this URL, I want to extract the first image which is on display and put it in the second column of my excel sheet.

I'm using this VBA Code, but all it does is get the logo from the site and puts it in the second column. Please note: All my references are in place and code is working, its just I'm not getting the image on display.
VBA Code:
Option Explicit

Public Sub InsertPicturesFromWeb()
    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim imgElements As IHTMLElementCollection
    Dim imgElement As HTMLImg
    Dim aElement As HTMLAnchorElement
    Dim N As Integer, I As Integer
    Dim Url As String, Url2 As String
    Dim LastRow As Long
    Dim M, sImageSearchString
   
    LastRow = Range("A" & Rows.Count).End(xlUp).Row
   
    For I = 1 To LastRow
        Url = "https://www.babyshopstores.com/ae/en/p/" & Cells(I, 1)
        Set IE = New InternetExplorer
       
        With IE
            .Visible = True
            .Navigate Url
           
            Do Until .readyState = 4: DoEvents: Loop
                Set HTMLdoc = .document
               
                Set imgElements = HTMLdoc.getElementsByTagName("IMG")
               
                N = 1
                For Each imgElement In imgElements
                    If InStr(imgElement.src, sImageSearchString) Then
                        If imgElement.ParentNode.nodeName = "A" Then
                            Set aElement = imgElement.ParentNode
                           
                            Url2 = imgElement.src
                            N = N + 1
                        End If
                    End If
                Next
               
                Call GetShapeFromWeb(Url2, Cells(I, 2))
               
                IE.Quit
                Set IE = Nothing
            End With
        Next I
End Sub

Sub GetShapeFromWeb(strShpUrl As String, rngTarget As Range)
   With rngTarget.Parent
      .Pictures.Insert strShpUrl
      .Shapes(.Shapes.Count).Left = rngTarget.Left
      .Shapes(.Shapes.Count).Top = rngTarget.Top
   End With
End Sub

My data for first column is the product number, which merges with the link in the given code. It searches but returns the logo, I want it to return the first display image and put it in the next column.
 
Upvote 0
From what I understand, that pages expose only the address of the thumbnails; and access to the server that hosts the thumbnails is password protected.

Anyway, try replacing this block
Rich (BB code):
                Set imgElements = HTMLdoc.getElementsByTagName("IMG")
                N = 1
                For Each imgElement In imgElements
                    If InStr(imgElement.src, sImageSearchString) Then
                        If imgElement.ParentNode.nodeName = "A" Then
                            Set aElement = imgElement.ParentNode
                            Url2 = imgElement.src
                            N = N + 1
                        End If
                    End If
                Next

with these two lines:
VBA Code:
                Set HTMLdoc = .document                        'Existing'
               
                Set oObj = HTMLdoc.getElementById("thmb-01")   'ADD
                Url2 = oObj.src                                'ADD
               
                Call GetShapeFromWeb(Url2, Cells(I, 2))        'Existing
This will let you import the thumbnails, but at each insertion you will be asked for a password; you can skip the authentication by pressing ESC

I also recommand you wait for IE not busy before waiting for the correct ReadyState; so add this line in this position:
Code:
            .Navigate Url
           
            Do While .Busy: DoEvents: Loop    'wait not busy, ADD
            Do Until .readyState = 4: DoEvents: Loop

And it is better that you declare the oObj variable that is used by the added lines, at the beginning of the Sub:
Code:
Dim oObj As Object

Bye
 
Upvote 0
Solution
Thank you so much @Anthony47. Is there anyway that I can bunk the authentication ? As I have data for almost 1000 rows.
 
Upvote 0
We could get better results by first downloading the image and then inserting (Note***) it into the worksheet.
So let's modify the code for the Sub InsertPicturesFromWeb this way:
Code:
Public Sub InsertPicturesFromWeb()
    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim I As Integer
    Dim URL As String, Url2 As String
    Dim LastRow As Long
    Dim oObj As Object, nPicName
'
    LastRow = Range("A" & Rows.Count).End(xlUp).Row
    Set IE = New InternetExplorer
    For I = 1 To LastRow
        URL = "https://www.babyshopstores.com/ae/en/p/" & Cells(I, 1)
        With IE
            .Visible = True
            .Navigate URL
            Do While .Busy: DoEvents: Loop    'wait not busy, ADD
            Do Until .readyState = 4: DoEvents: Loop
            Set HTMLdoc = .document
            Set oObj = HTMLdoc.getElementById("thmb-01")
            Url2 = oObj.src
            nPicName = GetWebFile(Url2, "C:\PROVA\")
            If nPicName <> 0 Then
                With ActiveSheet
                    .Pictures.Insert nPicName
                    .Shapes(.Shapes.Count).Left = Cells(I, 2).Left
                    .Shapes(.Shapes.Count).Top = Cells(I, 2).Top
                End With
            End If
        End With
    Next I
    IE.Quit
    Set IE = Nothing
End Sub

The line marked <<< need to be customized with a valid path to your disc; the images will be downloaded there.
This new version does no longer require the Sub GetShapeFromWeb, that can be deleted; but require this new Function GetWebFile:
Code:
#If VBA7 Then
    Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
        Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
        ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#Else
    Private Declare Function URLDownloadToFile Lib "urlmon" _
    Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If


  
Function GetWebFile(ByVal myURL, ByVal myPath As String) As Variant
'byAnthony, ritorna Image Path & name OPPURE 0 se fail
Dim PathNName As String, URL As String
Dim mySplit, Resp As Long
mySplit = Split(myURL, "/")
PathNName = myPath & mySplit(UBound(mySplit))
Resp = URLDownloadToFile(0, myURL, PathNName, 0, 0)
If Resp = 0 Then
    GetWebFile = PathNName
    Exit Function
Else
    GetWebFile = 0
End If
End Function
Beware that the initial declaration has to be put ON TOP of the vba module, before any other Sub or Function; so my suggestion is that you copy this second block of code into a new, just created, vba module.

***Note that Pictures.Insert set a LINK to the image, does not embed the images themselves into the workbook; in case you plan sharing the file with someone else the images will not be visible.
If this is your situation then we will use Shapes.AddPicture: this will make your file "fatter" as the images travel with the file.

Bye
 
Upvote 0
We could get better results by first downloading the image and then inserting (Note***) it into the worksheet.
So let's modify the code for the Sub InsertPicturesFromWeb this way:
Code:
Public Sub InsertPicturesFromWeb()
    Dim IE As InternetExplorer
    Dim HTMLdoc As HTMLDocument
    Dim I As Integer
    Dim URL As String, Url2 As String
    Dim LastRow As Long
    Dim oObj As Object, nPicName
'
    LastRow = Range("A" & Rows.Count).End(xlUp).Row
    Set IE = New InternetExplorer
    For I = 1 To LastRow
        URL = "https://www.babyshopstores.com/ae/en/p/" & Cells(I, 1)
        With IE
            .Visible = True
            .Navigate URL
            Do While .Busy: DoEvents: Loop    'wait not busy, ADD
            Do Until .readyState = 4: DoEvents: Loop
            Set HTMLdoc = .document
            Set oObj = HTMLdoc.getElementById("thmb-01")
            Url2 = oObj.src
            nPicName = GetWebFile(Url2, "C:\PROVA\")
            If nPicName <> 0 Then
                With ActiveSheet
                    .Pictures.Insert nPicName
                    .Shapes(.Shapes.Count).Left = Cells(I, 2).Left
                    .Shapes(.Shapes.Count).Top = Cells(I, 2).Top
                End With
            End If
        End With
    Next I
    IE.Quit
    Set IE = Nothing
End Sub

The line marked <<< need to be customized with a valid path to your disc; the images will be downloaded there.
This new version does no longer require the Sub GetShapeFromWeb, that can be deleted; but require this new Function GetWebFile:
Code:
#If VBA7 Then
    Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
        Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
        ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#Else
    Private Declare Function URLDownloadToFile Lib "urlmon" _
    Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If


 
Function GetWebFile(ByVal myURL, ByVal myPath As String) As Variant
'byAnthony, ritorna Image Path & name OPPURE 0 se fail
Dim PathNName As String, URL As String
Dim mySplit, Resp As Long
mySplit = Split(myURL, "/")
PathNName = myPath & mySplit(UBound(mySplit))
Resp = URLDownloadToFile(0, myURL, PathNName, 0, 0)
If Resp = 0 Then
    GetWebFile = PathNName
    Exit Function
Else
    GetWebFile = 0
End If
End Function
Beware that the initial declaration has to be put ON TOP of the vba module, before any other Sub or Function; so my suggestion is that you copy this second block of code into a new, just created, vba module.

***Note that Pictures.Insert set a LINK to the image, does not embed the images themselves into the workbook; in case you plan sharing the file with someone else the images will not be visible.
If this is your situation then we will use Shapes.AddPicture: this will make your file "fatter" as the images travel with the file.

Bye
Hey Anthony,

1. I have to send this file to someone, he can then run on his system and get this code working right ?

2. I'm getting an error.
Code.PNG
 
Upvote 0
I realize your platform is MacOS, whereas URLDownloadToFile is an API for the Windows platform, and I don't know if Mac has any equivalent function. This makes useless for you the "Function GetWebFile", that was in charge for downloading the image to your local file system.

Also I guess Mac has a different syntax for path and filename; this affects the following instruction:
VBA Code:
nPicName = GetWebFile(Url2, "C:\PROVA\")           '<<< A VALID PATH
You should use a valid path where the images would be saved into (include the path separator at the end)

But this information is useless given that GetWebFile cannot be used on your platform.

I AM SORRY but I am not able to help :mad:
 
Upvote 0
Hey Anthony, I'm doing this coding on Windows 10. It's working now, I just had to change the directory. Thank you so much.
 
Upvote 0
Good to know...
So now we need to embed the pictures into the workbook (rather than linking them to the pictures)

For this, replace this block
Rich (BB code):
            If nPicName <> 0 Then
                With ActiveSheet
                    .Pictures.Insert nPicName
                    .Shapes(.Shapes.Count).Left = Cells(I, 2).Left
                    .Shapes(.Shapes.Count).Top = Cells(I, 2).Top
                End With
            End If

With this:
Code:
            If nPicName <> 0 Then
                Set newPic = ActiveSheet.Shapes.AddPicture(nPicName, msoFalse, msoTrue, Cells(I, 2).Left, Cells(I, 2).Top, -1, -1)
            End If
On top of the macro it is good that you declare the new variable: Dim newPic As Variant

In this way, you can share the workbook with other users (even MacOs users) and they will be able to see the pictures

Bye
 
Upvote 0

Forum statistics

Threads
1,215,064
Messages
6,122,941
Members
449,094
Latest member
teemeren

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top