如何使用ComboBox提取信息表单XML文件?

时间:2019-05-21 20:49:04

标签: excel xml vba

我有一个包含很多信息的XML文件。 因此,我想在VBA Excel中创建一个宏,该宏可让我根据 accountID (可从用户窗体-ComboBox使用)

过滤信息。

这是我第一次使用XML和用户窗体。

我试图调整在网上找到的多个代码,但是我对此理解得更好,所以我想继续做类似的事情(如果可能的话):

Private Sub ComboBox1_Click()
    Dim wks As Worksheet
    Set wks = Sheet2

    ' Load the XML document
    Dim XDoc As Object, root As Object
    Set XDoc = CreateObject("MSXML2.DOMDocument")
    XDoc.async = False: XDoc.validateOnParse = False
    XDoc.Load ("C:\Users\isabelle\Google Drive\IB API Integration\Flexqueries\FlexDay.xml") 

    Dim singleNode As Object
    Set singleNode = XDoc.SelectSingleNode("//FlexQueryResponse/FlexStatements/FlexStatement[@accountId='U2396623']")

End Sub

accountId'U2396623'仅是一个示例。这将与组合框中的条目相对应。

我的两个问题是:

  1. 首先,我不知道如何将组合框中的条目链接到代码(基于accountID)

  2. 第二,上面的代码不起作用。我认为路径(XDoc.SelectSingleNode)是不正确的...因此,我捆绑了几种组合,但从未成功。也许是输出无法正常工作(输出应在 Sheet2 中)

我的XML文件如下:

<FlexQueryResponse queryName="Sample_1" type="AF">
   <FlexStatements count="10">
      <FlexStatement accountId="" fromDate="2019-04-22" toDate="2019-05-21" period="Last30CalendarDays" whenGenerated="2019-05-22;13:49:30">
         <AccountInformation accountId="" acctAlias="" currency="CAD" accountType="Advisor Client" dateOpened="2018-02-08" dateFunded="2018-03-01" dateClosed="" street="" street2="" city="" state="" country="" postalCode="" primaryEmail="" />
         <ChangeInNAV accountId="" acctAlias="" startingValue="" endingValue="" realized="0" changeInUnrealized="0" depositsWithdrawals="0" twr="" mtm="" dividends="" changeInDividendAccruals="" interest="" changeInInterestAccruals="" advisorFees="" clientFees="0" otherFees="0" />
         <CashReport>
            <CashReportCurrency accountId="" acctAlias="" clientFees="0" commissions="" deposits="0" withdrawals="0" accountTransfers="0" dividends="" advisorFees="" otherFees="0" currency="BASE_SUMMARY" startingCash="" endingCash="" endingSettledCash="" />
            /&gt;
         </CashReport>
         <OpenPositions>
            <OpenPosition accountId="" acctAlias="" symbol="" position="" costBasisPrice="" strike="" expiry="" putCall="" positionValue="" percentOfNAV="" fifoPnlUnrealized="" currency="CAD" fxRateToBase="1" assetCategory="STK" description="BOMBARDIER INC PFD SER 2" securityID="CA0977515075" cusip="" isin="CA0977515075" />
         </OpenPositions>
         <FxPositions>
            <FxPosition accountId="" fxCurrency="CAD" quantity="" costPrice="" unrealizedPL="0" />
         </FxPositions>
         <OptionEAE>
            <OptionEAE accountId="" acctAlias="" currency="USD" assetCategory="" symbol="" description="" securityID="" cusip="" isin="" listingExchange="" underlyingConid="" underlyingSymbol="FCAU" underlyingSecurityID="NL0010877643" underlyingListingExchange="NYSE" issuer="" strike="16" expiry="2019-05-03" putCall="C" date="2019-04-22" transactionType="Assignment" quantity="2" tradePrice="0.0000" markPrice="0.3500" realizedPnl="0.00" />
         </OptionEAE>
         <PendingExcercises />
         <ClientFees />
         <OpenDividendAccruals>
            <OpenDividendAccrual accountId="" acctAlias="" currency="" assetCategory="" symbol="" description="" securityID="" cusip="" isin="" exDate="2019-05-03" payDate="2019-06-24" quantity="400" grossRate="0.23" grossAmount="92" netAmount="92" />
         </OpenDividendAccruals>
      </FlexStatement>
   </FlexStatements>
</FlexQueryResponse>

如果您有任何疑问,请不要犹豫!

谢谢您的帮助

1 个答案:

答案 0 :(得分:0)

考虑一些调整:

  1. 使用组合框的 AfterUpdate 触发事件。

    Private Sub ComboBox1_AfterUpdate()
        ...
    End Sub
    
  2. 只需将组合框值Me.ComboBox1连接到XPath表达式。

    XDoc.SelectSingleNode("/FlexQueryResponse/FlexStatements/FlexStatement[@accountId='" & Me.ComboBox1 & "']")
    
  3. 选择所需的属性值,或按多个节点循环遍历以提取到工作表。

    Private Sub ComboBox1_AfterUpdate()
        ' Load the XML document
        Dim XDoc As Object, root As Object, singleNode As Object
        Dim i As Integer
    
        Set XDoc = CreateObject("MSXML2.DOMDocument")
    
        XDoc.async = False: XDoc.validateOnParse = False
        XDoc.Load ("C:\Users\isabelle\Google Drive\IB API Integration\Flexqueries\FlexDay.xml")
    
        ' OUTPUT ONE ATTRIBUTE OF NODE
        Set singleNode = XDoc.SelectSingleNode("/FlexQueryResponse/FlexStatements/FlexStatement[@accountId='" & Me.ComboBox1 & "']")
        ThisWorkbook.Worksheets("Sheet1").Range("A1") =  singleNode.Attributes.getNamedItem("accountId").Text
    
        ' OUTPUT ALL ATTRIBUTES OF NODE
        For i = 0 To singleNode.Attributes.Length - 1
             ThisWorkbook.Worksheets("Sheet1").Range("A" & i + 1) = singleNode.Attributes(i).Name
             ThisWorkbook.Worksheets("Sheet1").Range("B" & i + 1) = singleNode.Attributes(i).Text
        Next i
    
        Set XDoc = Nothing
    End Sub
    

    Excel Output