【问题标题】:Referencing Cells in Excel Web Power Query在 Excel Web Power Query 中引用单元格
【发布时间】:2019-01-30 20:35:05
【问题描述】:

我正在尝试创建一个自动从该网站获取数据的 Excel 文件 (https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTSTK&symbol=SBIN&date=31JAN2019)

我可以根据 Excel 单元格值更改符号。虽然我无法从电源查询中创建它。我尝试了 VBA 宏,但第一次尝试它可以工作,但后来由于现有表而显示错误。这是我完成的 VBA 代码。

Sub OptionChain()
'
' OptionChain Macro
'
TICKER = Sheets("Sheet1").Cells(1, 1)

Sheets("Sheet2").Select
Cells.Clear
'
ActiveWorkbook.Queries.Add Name:="Table 0", Formula:= _
    "let" & Chr(13) & "" & Chr(10) & "    Source = Web.Page(Web.Contents(""https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTSTK&symbol=" & TICKER & "&date=31JAN2019""))," & Chr(13) & "" & Chr(8) & "    Data0 = Source{0}[Data]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Data0,{{""CALLS OI"", type text}, {""CALLS Chng in OI"", type" & _
    " text}, {""CALLS Volume"", type text}, {""CALLS IV"", type text}, {""CALLS LTP"", type text}, {""CALLS Net Chng"", type text}, {""CALLS Bid Qty"", type text}, {""CALLS Bid Price"", type text}, {""CALLS Ask Price"", type text}, {""CALLS Ask Qty"", type text}, {""Strike Price"", type number}, {""PUTS Bid Qty"", type text}, {""PUTS Bid Price"", type text}, {""PUTS Ask " & _
    "Price"", type text}, {""PUTS Ask Qty"", type text}, {""PUTS Net Chng"", type text}, {""PUTS LTP"", type text}, {""PUTS IV"", type text}, {""PUTS Volume"", type text}, {""PUTS Chng in OI"", type text}, {""PUTS OI"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""


With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""Table 0"";Extended Properties=""""" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandType = xlCmdSql
    .CommandText = Array("SELECT * FROM [Table 0]")
    .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_0"
    .Refresh BackgroundQuery:=False
End With

谁能帮助我如何从单元参数创建网络电源查询。

谢谢。

【问题讨论】:

    标签: excel vba web-scraping powerquery


    【解决方案1】:

    如果你不介意一点点家务并且没有图表,你可以使用 xmlhttp

    Option Explicit
    Public Sub GetTable()
        Dim sResponse As String, html As HTMLDocument, clipboard As Object, ws As Worksheet, shp As Shape, wsSource As Worksheet
        Set wsSource = ThisWorkbook.Worksheets("symbols")
        Set ws = ThisWorkbook.Worksheets("Sheet1")
        Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
        ws.Cells.Clear
        ws.Cells.UnMerge
    
        With CreateObject("MSXML2.XMLHTTP")
            .Open "GET", "https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTSTK&symbol=" & wsSource.Cells(1, 1) & "&date=31JAN2019", False
            .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
            .send
            sResponse = StrConv(.responseBody, vbUnicode)
        End With
        Set html = New HTMLDocument
        html.body.innerHTML = sResponse
    
        clipboard.SetText html.querySelectorAll("table").Item(2).outerHTML
        clipboard.PutInClipboard
        ws.Cells(1, 1).PasteSpecial
        ClearCharts ws
    End Sub
    

    一个冗长的方法是:

    Option Explicit
    Public Sub WriteOutTable()
        Dim sResponse As String, html As HTMLDocument, ws As Worksheet, wsSource As Worksheet, hTable As HTMLTable
        Set wsSource = ThisWorkbook.Worksheets("symbols")
        Set ws = ThisWorkbook.Worksheets("Sheet1")
        ws.Cells.Clear
        With CreateObject("MSXML2.XMLHTTP")
            .Open "GET", "https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTSTK&symbol=" & wsSource.Cells(1, 1) & "&date=31JAN2019", False
            .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
            .send
            sResponse = StrConv(.responseBody, vbUnicode)
        End With
        Set html = New HTMLDocument
        html.body.innerHTML = sResponse
        Set hTable = html.querySelector("#octable")
    
        Dim tr As Object, td As Object, i As Long, th As Object, r As Long, c As Long, lastRow As Long
        lastRow = hTable.getElementsByTagName("tr").Length
        For Each tr In hTable.getElementsByTagName("tr")
            r = r + 1: c = 1
            Select Case r
            Case 1
                ws.Cells(r, 1) = tr.getElementsByTagName("th")(0).innerText
                ws.Cells(r, 12) = tr.getElementsByTagName("th")(2).innerText
            Case 2
                For Each th In tr.getElementsByTagName("th")
                    If Not th.title = "Chart" Then
                        c = c + 1
                        ws.Cells(r, c) = th.title
                    End If
                Next
            Case lastRow
                ws.Cells(r, 1) = "Total"
                ws.Cells(r, 2) = tr.getElementsByTagName("td")(1).innerText
                ws.Cells(r, 3) = tr.getElementsByTagName("td")(3).innerText
                ws.Cells(r, 19) = tr.getElementsByTagName("td")(5).innerText
                ws.Cells(r, 21) = tr.getElementsByTagName("td")(7).innerText
            Case Else
                c = 2
                For Each td In tr.getElementsByTagName("td")
                    If td.classname = "ylwbg" Or td.classname = "nobg" Or td.classname = "grybg" Then
                        ws.Cells(r, c) = td.innerText
                        c = c + 1
                    End If
                Next
            End Select
        Next
    End Sub
    

    【讨论】:

      【解决方案2】:

      您可以使用 Power Query 通过定义命名范围来引用单元格值。

      所以您的查询可能类似于:

      let
          Symbol = Excel.CurrentWorkbook(){[Name="MySymbol"]}[Content]{0}[Column1],
          Date = Text.Upper(DateTime.ToText(DateTime.LocalNow(),"ddMMMyyyy")),
          Source = Web.Page(Web.Contents("https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?segmentLink=17&instrument=OPTSTK&symbol=" & Symbol & "&date=" & Date)),
          Data = Source{0}[Data],
          #"Change Type" = Table.TransformColumnTypes(Data, List.Transform(Table.ColumnNames(Data), each {_, type number})),
          #"Replace Errors" = Table.ReplaceErrorValues(#"Change Type", List.Transform(Table.ColumnNames(#"Change Type"), each {_, null}))
      in
          #"Replace Errors"
      

      现在您可以更改单元格“MySymbol”中的符号并简单地刷新查询。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-06
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        相关资源
        最近更新 更多