HTML到Excel +更改页面循环

错误说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 

docNothing 。 因为你基本上正在做Set Nothing.getElementById("Pages").Value = CStr(i)

但是当我试图将doc定义为文档或word文档时

那么你需要澄清发生了什么,因为这不是你可以使用Word Document对象的语法,而是一个网页.Document 。 既然你正在使用QueryTables ,我假设后者:

为了解决这个问题,你需要首先创build一个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 IntegerLong ,而不是String,否则这行可能会引起一个不匹配的错误: i = i + 1