图像尺寸

时间:2013-04-28 22:56:57

标签: excel vba

我需要一个excel中的VBA代码来确定来自给定Web链接的图像的尺寸。 以下是我创建的代码;

Sub ccheck()
Dim ie As New InternetExplorer

Dim path As String
ie.Visible = True

path = Sheet1.Range("A1").Value
ie.navigate path

Do
DoEvents
Loop Until ie.readyState = READYSTATE_COMPLETE

Dim doc As HTMLDocument
Set doc = ie.document
Dim sdd As String
Dim size As String

For i = 1 To 20
sdd = Trim(doc.getElementsByTagName("img")(i).src)
size = Trim(doc.getElementsByTagName("img")(i).Width) + "x" + Trim(doc.getElementsByTagName("img")(i).Height)
Sheet2.Range("A" & i).Value = path
Sheet2.Range("B" & i).Value = sdd
Sheet2.Range("C" & i).Value = size
Next i

End Sub

但问题是,如果网站的源代码中没有给出height或width属性,脚本会将值赋给零。

除了代码中给出的方法之外,还有其他方法来获取图像尺寸。

请帮助我和vba新手一样。任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

对代码进行了一些修改。

Sub ccheck()
    On Error Resume Next
    Dim ie As New InternetExplorer

    Dim path As String
    ie.Visible = True

    path = "http://stackoverflow.com/questions/16268923/image-dimensions"
    ie.navigate path

    Do
        DoEvents
    Loop Until ie.readyState = READYSTATE_COMPLETE

    Dim doc As HTMLDocument
    Set doc = ie.document

    Dim sdd As String
    Dim size As String

    Dim imgEle As Object
    Set imgEle = doc.getElementsByTagName("img")

    Dim i As Object, j As Long

    j = 1
    For Each i In imgEle
        sdd = Trim(i.src)
        size = Trim(i.Width) + "x" + Trim(i.Height)
        Sheet2.Range("A" & j).Value = path
        Sheet2.Range("B" & j).Value = sdd
        Sheet2.Range("C" & j).Value = size
        j = j + 1
    Next

End Sub