Excel VBA - 从html复制文本并粘贴到excell

时间:2018-05-24 16:14:10

标签: excel vba excel-vba

我希望从特定网站复制数据并将信息粘贴到Excel中。 我创建了一个搜索框,您可以输入项目代码,例如“CPINT00038”,它将打开特定页面。 但是对于我的生活,我无法弄清楚如何抓取图像和文本并将它们粘贴到excel中。

这是我的代码到目前为止请帮助

Sub SearchCC()

'what to search for

Dim SearchString As String

SearchString = InputBox("What do you want to search for?")

'create and a new instance of IE

Dim IE As New InternetExplorer

IE.Visible = True

'to find what you're looking for

IE.Navigate "http://www.canadacomputers.com/search_results.php? 
search_in=&keywords=" & SearchString

While IE.Busy Or IE.ReadyState <> 4: DoEvents: Wend

End Sub

1 个答案:

答案 0 :(得分:0)

对于描述而言,它非常简单,只需一次性将其变为变量:

description = IE.Document.getElementById("desc1").getElementsByTagName("p")(0).innerText

...然后将其打印到所需的位置Range("A1").Value = description

对于图像来说,它有点棘手。要从网上下载图像,您可以:

1)在模块顶部添加库URLDownloadToFile提供的urlmon.dll函数的声明(注意:如果您的Excel是32位而不是64位,则需要删除关键字PtrSafe):

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

2)使用这样的函数将图像保存到给定名称的给定路径中:

samplePath = "C:\Users\Yourself\YourFolder\yourImage.jpg"
imgSource = IE.Document.getElementsByClassName("prodimg")(0).getAttribute("src")
Response = URLDownloadToFile(0, imgSource, samplePath, 0, 0)

如果Response等于0,则图片已成功从网上下载并保存到&#34; C:\ Users \ Yourself \ YourFolder \ yourImage.jpg&#34;。< / p>

我允许您录制宏以从给定路径在Excel中插入图像(让我们调用此宏Sub InsertImage(ByVal filePath As String),然后只需:

If Response = 0 Then
    InsertImage samplePath
End If

然后,您可以从计算机as explained in this answer

中删除下载的图像