错误说Object variable or With block variable are not set
。但是,当我试图将doc定义为文档或word文档时,它只是不允许这样做。在此先感谢!!!
Sub HTMLtoExcel()
Dim doc As Object
Dim i As String
i = 1
Do While i <= 1783
Set doc.getElementById("Pages").Value = CStr(i)
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http:/xxx.yyy" _
, Destination:=Range("$A$1"))
.Name = _
"its_details_value_node.html?nsc=true&listId=www_s201_b9233&tsId=BBK01.ED0439"
.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
i = i + 1
Loop
End Sub
答案 0 :(得分:1)
doc
是Nothing
。这条线正在破裂,因为你基本上在做Set Nothing.getElementById("Pages").Value = CStr(i)
但是当我试图将doc定义为文档或word文档时
您需要澄清发生了什么,因为这不是可以与Word Document
对象一起使用的语法,而是网页.Document
。由于您使用QueryTables
,我假设后者:
要解决此问题,您需要先创建一个Web浏览器实例,然后设置doc
,例如:
Dim ie as Object
Set ie = CreateObject("Internet.Explorer")
ie.Navigate "http://google.com" 'Modify as needed
Do While ie.ReadyState <> 4 And Not ie.Busy
DoEvents
'It is better to use the WinAPI sleep function
' there are several examples of implementing this here on SO
Loop
Set doc = ie.Document
考虑到这一点,这条线没有任何意义:
Set doc.getElementById("Pages").Value = CStr(i)
对于初学者,.Value
不是对象,因此您无法Set
它。此外,getElementByID
返回对象。也许你想要:
doc.getElementById("Pages").Value = Cstr(i)
现在你有一个循环正在执行1783次,但它不能按预期工作,因为你没有改变QueryString
中的任何参数,所以如果它确实工作了1783次,它就是每次都要提取相同的数据。如果您遇到问题,则要求将其作为单独的/新问题。
您还需要Dim i as Integer
或Long
,而不是此上下文中的字符串,否则此行可能会引发不匹配错误:i = i + 1
。