gpt4 book ai didi

excel - 已存在具有该名称的查询

转载 作者:行者123 更新时间:2023-12-04 20:25:16 24 4
gpt4 key购买 nike

所以我想使用 Excel VBA 为 Yahoo Finance 历史数据(csv 下载)创建一个自动查询。我设置了一个函数,以便 Excel 会自动查询股票代码及其开始和结束日期(分别为 K1、K2、K3)。

这是代码:

Sub YFIN_get()
'
' YFIN_get Macro
'
Dim ticker As String, sday, eday As Long
Columns("A:G").ClearContents
ticker = Range("K1")
sday = Range("K2")
eday = Range("K3")
'
ActiveWorkbook.Queries.Add Name:="Table 4", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(Web.Contents(""https://query1.finance.yahoo.com/v7/finance/download/" & ticker & "?period1=" & sday & "&period2=" & eday & "&interval=1d&events=history""),[Delimiter="","", Columns=7, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & " #""Use First Row as Headers"" = Table.PromoteHeaders(Source, [PromoteAllScalars=true])," & Chr(13) & "" & Chr(10) & " #""Change Type"" = Table" & _
".TransformColumnTypes(#""Use First Row as Headers"",{{""Date"", type date}, {""Open"", type number}, {""High"", type number}, {""Low"", type number}, {""Close"", type number}, {""Adj Close"", type number}, {""Volume"", Int64.Type}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " #""Change Type"""
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Table 4"";Extended Properties="""""), Destination:=Range("$A$1")). _
QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [Table 4]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_4"
.Refresh BackgroundQuery:=False
End With
Application.CommandBars("Queries and Connections").Visible = False
End Sub

但是,每当我第二次运行代码时,VBA 总是会检索运行时错误“名称为‘表 4’的查询已经存在”。当我调试错误时,它会突出显示 ActiveWorkbook.Queries.Add 名称..... 部分。

有人可以帮我解决问题吗?也许删除查询?如果是这样,我应该如何删除查询? (我对 VBA 完全陌生,因此非常感谢您的帮助)

最佳答案

您可以在尝试添加之前使用它:

On Error Resume Next
ActiveWorkbook.Queries("Table 4").Delete
On Error GoTo 0

关于excel - 已存在具有该名称的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61767220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com