VBA code to click Image in WebBrowser control.

Artik

Active Member
Joined
Jun 5, 2012
Messages
286
Hello exceloholics.
I need a solution using the WebBrowser control on Userform (Windows 11, MSO 365). As with loading the control with images I didn't have major problems, but with the response to clicking on images I fell. I tried all day to get Copilot to write the missing code. But it was like kicking myself with a horse, I had to lose.
I need functionality so that when clicking on images loaded into a WebBrowser control, the selected image displays in the other control. Unfortunately, HTML, JavaScript is not my garden so I can't think of much here. Here is the code that loads the images into the WebBrowser.
VBA Code:
Private Sub UserForm_Initialize()
    Call LoadClickableImagesInWebBrowser
End Sub


Sub LoadClickableImagesInWebBrowser()
    Dim folderPath As String
    Dim imgSpacing As String
    Dim htmlContent As String
    Dim fileName As String
    Dim filePath As String
    Dim imgTag As String
    Dim FSO As Object
    Dim folder As Object
    Dim file As Object
    Dim i As Long


    folderPath = ThisWorkbook.Path & "\"
    imgSpacing = "6px"

    htmlContent = "<html><body style='margin:0;padding:0;'>"

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder = FSO.GetFolder(folderPath)

    For Each file In folder.Files
        fileName = file.Name
        If LCase(fileName) <> LCase("NoPicture.jpg") And LCase(fileName) <> LCase(ThisWorkbook.Name) And (fileName Like "[!~]*") Then
            i = i + 1
            filePath = folderPath & fileName
            imgTag = "<img id='img" & i & "' src='" & filePath & "' width='70' height='70' style='display:block; margin-bottom:6px;'>"
            htmlContent = htmlContent & imgTag
        End If
    Next file

    htmlContent = htmlContent & "</body></html>"

    On Error GoTo Err_Hndl

    Me.WebBrowser2.Navigate "about:blank"

    Do While Me.WebBrowser2.ReadyState <> 4
        DoEvents
    Loop

    Me.WebBrowser2.Document.Open
    Me.WebBrowser2.Document.Write htmlContent
    Me.WebBrowser2.Document.Close

    Me.WebBrowser2.Document.body.Style.overflowY = "auto"

    Exit Sub
Err_Hndl:
    Debug.Print Err.Number & " ; " & Err.Description
End Sub
In the attachment I also show a solution using Frame and dynamically adding Image controls. I would like to achieve the same functionality in the second UserForm.
Why can't I use the solution with Frame? Because there are more than 4K possible images to display (at most 20 in one session), which have different formats that are not supported by the Image control (including PNG).

And also an overview image

Screenshot 02.10.24.png


Artik
 

Excel Facts

Format cells as time
Select range and press Ctrl+Shift+2 to format cells as time. (Shift 2 is the @ sign).
Why can't I use the solution with Frame? Because there are more than 4K possible images to display (at most 20 in one session), which have different formats that are not supported by the Image control (including PNG).
It's true that VBA does not natively support PNG files, but there are solutions. The easiest, I think, is one I wrote about here: Working with images in VBA - Displaying PNG files

The short version of it is that you can load PNG files into ImageBox controls with a few short lines:

VBA Code:
Function LoadImage(ByVal Filename As String) As StdPicture
  With CreateObject("WIA.ImageFile")
    .LoadFile Filename
    Set LoadImage = .FileData.Picture
  End With
End Function

Any other image files you need to use? There are ways where you could even load WEBP if you absolutely had to.
 
Upvote 0
I apologize for the delay of a few days, other things were more important at the time. Life itself.
The LoadImage function shown, which uses WIA, worked very well. It also coped with PNG files that had previously been changed to JPG extension.
I talked to the client about how it collected the image files it needed. In the conversation, it turned out that he was using Selenium to download files from websites, but to all change the original extensions to JPG. Many graphics browsers can handle such fake JPG files, so the client didn't notice the problem. But in VBA it doesn't work. Such files cannot be imported into standard controls. The LoadImage function can certainly handle PNG files that have been changed to JPG extension.
I looked at the websites from which the client downloads files and noticed that in addition to JPG, JPEG, PNG, there will also be AVIF and WEBP files to download. Therefore, I am interested in continuing this thread if possible.

Artik
 
Upvote 0
I would have to convert some VB6 code to 64bit compatible VBA code, so give me a few days.

Did you get to read the whole article I linked to above? Because there is a function in there that allows you to get images from the web direct into WIA, and into your userform control:

VBA Code:
    Function GetImageFromURL(ByVal TargetURL As String) As StdPicture

        Dim HTTP            As Object
        
        Set HTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
        HTTP.Open "GET", TargetURL, False
        HTTP.send

        If HTTP.Status = 200 Then
            With CreateObject("WIA.Vector")
                .BinaryData = HTTP.responseBody
                Set GetImageFromURL = .Picture
            End If
        End If

        Set HTTP = Nothing
        
    End Function

As for changing the extensions - they are PNG files. You can change it to Image1.WHATEVERYOULIKE, and they will still be PNG files. The WIA COM object can also convert image files, if required. Is that something you would need?
 
Upvote 0
Of course, I paid attention to the GetImageFromURL function (I'll leave Base64 alone for now). But I'm unlikely to go that route. There are at least two reasons. The first, the commodity identifiers that the client has are not the same as the file names on the pages. I would have to create a name conversion table in addition. I don't think the customer will agree to this.
The second reason is performance. Downloading data from a local file will be faster than downloading it from the web. The client is rather inclined to collect files locally. I just have to convince him to do the files in order. Especially with the ones he changed the extension to.
I am also considering using the ImageMagick tool. It allows you to use the command line. The basic conversion is very simple. Command line use (after installing the tool first, of course):
magick d:\test55899.avif d:\test55899.jpg
However, it is unlikely to be implemented in the project I am working on. It needs too much time to convert the file, so I won't use it for on-the-fly conversion.
Code for posterity who would like to use this tool in VBA:
VBA Code:
Sub ConvertAVIFtoJPG()
    Dim shell As Object
    Dim command As String

    Set shell = CreateObject("WScript.Shell")

    command = "powershell.exe -Command ""magick d:\test5\5899.avif d:\test5\5899.jpg"""
    
    shell.Run command, 0, True

    Set shell = Nothing
End Sub

Artik
 
Upvote 0

Forum statistics

Threads
1,223,869
Messages
6,175,087
Members
452,611
Latest member
bls2024

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