编译错误:需要常量表达式

时间:2014-12-21 15:05:13

标签: vba excel-vba excel

我偶然发现了一个编译错误,但没有得到可能存在的问题。当试图将符号变换为输入变量(TickerID)时,我得到错误,否则在输入例如" yhoo"对于雅虎股票代码名称。

代码

Private Sub CmdBtn_Add_Click()
'---------------------------------------------------------------------------------------'
' Checks that inputted ticker name is correct and calls import class after confirmation
'---------------------------------------------------------------------------------------'

' General Variables---------'
  Dim TickerID As String: TickerID = UCase(Add_Instrument.TxtBox_Instrument.Value)
'--------------------------'

    'Check if input field is not empty
    If TickerID = "" Or Application.WorksheetFunction.IsText(TickerID) = False Then
        MsgBox "Please provide a valid ticker ID"
        Exit Sub
    End If

    Debug.Print TickerID

    'Check Ticker name exists through YQLBuilder class
    Dim YQLBuilder As YQLBuilder: Set YQLBuilder = New YQLBuilder
    Call YQLBuilder.TickerCheck(TickerID)


'        Call ImportData(TickerID)

'        MsgBox "Please check the ticker name. It is in the wrong format"

End Sub
Public Sub TickerCheck(TickerID As String)
'---------------------------------------------------------------------------------------'
' Built 2014-11-05 Allows parsing of XML data through YAHOO API YQL
' 2014-12-21: Not fully built yet, see where it can be of use
'---------------------------------------------------------------------------------------'

' General Variables---------'
Const ConnStringStart As String = "http://query.yahooapis.com/v1/public/yql?q="
Const ConnStringLast As String = "&diagnostics=true&env=store://datatables.org/alltableswithkeys"
'---------------------------'


 Const ConnStringInput As String = "select * from yahoo.finance.stocks where symbol='" _
 & TickerID & "'" **<----- Error here!**

    Debug.Print ConnStringStart & ConnStringInput & ConnStringLast

    Dim YQLNodes As MSXML2.IXMLDOMNodeList
    Dim YQLReq As MSXML2.DOMDocument60

    Set YQLReq = New MSXML2.DOMDocument60

        YQLReq.async = False
        YQLReq.Load ConnStringStart & ConnStringInput & ConnStringLast

    YQLReq.setProperty "SelectionNamespaces", "xmlns:f='http://www.yahooapis.com/v1/base.rng'"
    Set YQLNodes = YQLReq.SelectNodes("//CompanyName")

    Dim xNode As MSXML2.IXMLDOMNode

    For Each xNode In YQLNodes

        Debug.Print xNode.Text

    Next xNode

     Debug.Print YQLNodes.Length

End Sub

1 个答案:

答案 0 :(得分:3)

信息很清楚。声明常量时,您给它的值也必须是常量。在这种情况下,它的一部分是参数TickerId,它是可变的。您不能使用变量值声明常量。

要解决这个问题,我认为你可以使用Dim代替Const,而不是让ConnStringInput成为常量。