1
我有一個電子表格,列A中有一列URL。我想要讀取每個URL並將輸出存儲在單個單元格中,或者至少將URL存儲到與URL相同的行中。我目前使用下面的標準VBA代碼來完成每次讀取(這裏簡化爲使用靜態URL)。Excel宏將Web數據導入單元格
問題是Excel根據網頁的格式(顯然是通常需要的),自動將數據分成多行和多列。
是否有任何簡單的方法來修改該代碼,強制輸出到單個單元格或行請?
Sub FetchData()
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://www.someurl", Destination:=Range("$B$1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
End Sub
別擔心,我設法使用代碼從這裏弄明白:下面 Fetch specific table only from website into Excel
我的版本假設A列中包含的URL列表,和列B-我其它數據。我想讀取列A中每個URL的網頁,並從表中提取2個字段,並將它們放入J和K列(第10和11列)。這些字段在網頁中被命名爲ID =「Name1」和ID =「Name2」。
Sub Getfromweb()
Dim RowNumb As Long
Dim LastRow As Long
Dim htm As Object
Set htm = CreateObject("htmlFile")
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
For RowNumb = 1 To LastRow
With CreateObject("msxml2.xmlhttp")
.Open "GET", Sheets(1).Cells(RowNumb, 1), False
.send
htm.body.innerhtml = .responsetext
End With
With htm.getelementbyid("Name1")
Sheets(1).Cells(RowNumb, 10).Value = .innertext
End With
With htm.getelementbyid("Name2")
Sheets(1).Cells(RowNumb, 11).Value = .innertext
End With
Next RowNumb
End Sub
你確實需要使用QueryTables方法嗎?你不能只是'CreateObject(「InternetExplorer.Application」)'然後使用該對象導航到URL,並返回'.Document.Body.InnerText'?但是,這當然不會保留格式。 –