Excel VBA - 似乎Ws命名错误

时间:2017-04-14 00:51:41

标签: excel vba excel-vba

我非常绝望,我继续遇到以下代码的VBA错误1004:

  Sub GetRawPrices()
  Dim wb As Workbook
  Dim ws As Worksheet
  Dim wq As QueryTable
  Dim url As String
  Dim wb0 As Workbook
  Set wb0 = ThisWorkbook
  Dim i As Integer
  For i = 2 To wb0.Worksheets("Consolidation").Range("A1").End(xlDown).Row Step 1
  Set wb = Workbooks.Add
  wb.SaveAs Filename:="G:\2015July\Desktop2\HORIZONTAL\" & wb0.Worksheets("Consolidation").Cells(i, 1).Value & ".xlsx"
  url = _
    "TEXT;" & _
    "http://ichart.finance.yahoo.com/table.csv?" & _
    "s=" & _
    wb0.Worksheets("Consolidation").Cells(i, 1).Value & _
    "&" & _
    "a=01&" & _
    "b=01&" & _
    "c=2015&" & _
    "d=03&" & _
    "e=12&" & _
    "f=2017&" & _
    "g=d&" & _
    "ignore=.csv"
  Set ws = wb.Worksheets.Add(After:=Sheet3)
  ws.Name = "YAHOO_DATA"
  Set wq = ws.QueryTables.Add( _
    Connection:=url, _
    Destination:=ws.Range("A1"))
  wq.TextFileParseType = xlDelimited
  wq.TextFileCommaDelimiter = True
  wq.Refresh BackgroundQuery:=False
  wb.Close savechanges:=True
  Next i

End Sub

我觉得下面两行有问题,因为我可以正确地创建并保存wb,而且我只会遇到错误1004,而不会创建新的工作表ws" YAHOO_DATA"。

  Set ws = wb.Worksheets.Add(After:=Sheet3)
  ws.Name = "YAHOO_DATA"

但可能有什么不对?我有另一个Excel文件运行几乎完全相同的代码,它运作良好...

如果有人能为我解决这个问题,我将不胜感激......自从我已经盯着这段代码以来已经有2个小时了!谢谢!

博斯科

1 个答案:

答案 0 :(得分:3)

更改以下行

Set ws = wb.Worksheets.Add(After:=Sheet3)

Set ws = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))

在某些MS Excel版本中,新工作簿没有创建3个新工作表。