2014年3月7日 星期五

VBA抓取恐慌指數(VIX指數)

用VBA抓取取恐慌指數,並且畫成曲線圖,有興趣研究,請參考如下程式碼。
Option Explicit

Sub GetVIX()
    Dim URL As String
    URL = "http://www.cboe.com/publish/ScheduledTask/MktData/datahouse/vixcurrent.csv"
    
    Application.ScreenUpdating = False
    
    ClaerChartObjects
 
    Workbooks(1).Worksheets(1).UsedRange.ClearContents

    With Workbooks.Open(URL)
        .Sheets("vixcurrent").UsedRange.Copy _
        Destination:=Workbooks(1).Worksheets(1).Cells(1, 1)
        .Close 0
    End With
    
    繪圖
    
    Application.ScreenUpdating = True
End Sub

Sub 繪圖()
    Dim nRow As Integer
    
    ClaerChartObjects
    
    nRow = Worksheets(1).Range("A65536").End(xlUp).Row
    With ActiveSheet.ChartObjects.Add(Left:=337, Top:=33, Width:=701, Height:=445).Chart
        With .SeriesCollection.NewSeries
            .ChartType = xlLine             '圖表類型
            .Values = Range("E3:E" & nRow)  '數值
            .XValues = Range("A3:A" & nRow) 'X軸
            .Name = "VIX"                   '圖表名稱
            .Border.Color = vbBlue          '顏色
        End With
    End With
End Sub

Sub ClaerChartObjects()
    Dim Chtobj As ChartObject
    
    For Each Chtobj In ActiveSheet.ChartObjects
        Chtobj.Delete
    Next
End Sub

執行畫面