[VBA]Vẽ biểu đồ từ dữ liệu mảng

tuhocvba

Administrator
Thành viên BQT
Trong bài viết này chúng ta sẽ thử tạo một biểu đồ từ dữ liệu mảng. Trình tự sẽ như dưới đây:
  • Tạo mảng
  • Tạo đồ thị mới
  • Thiết định kiểu đồ thị
  • Chèn dữ liệu thứ nhất
  • Chèn dữ liệu thứ hai
  • Chèn dữ liệu thứ ba
  • Chèn giải thích
Mã:
Sub TEST1()
    
    Dim A0, A1, A2
    Dim Kei, X
    
    'Creat array
    X = Array("Chuoi", "Cam", "Vai")
    Kei = Array("HungYen", "HaGiang", "HaiDuong")
    A0 = Array(1000, 400, 200) 'HungYen
    A1 = Array(300, 100, 1000) 'HaGiang
    A2 = Array(2000, 800, 300) 'HaiDuong
    
    'Add new graph
    ActiveSheet.Shapes.AddChart2.Select
    ActiveChart.ChartType = xlColumnClustered 'Type Bar
    
    'Cot du lieu thu nhat
    With ActiveChart.SeriesCollection.NewSeries
        .XValues = X '= Array("Chuoi", "Cam", "Vai")
        .Name = Kei(0) 'HungYen
        .Values = A0 '= Array(1000, 400, 200)
    End With
    
    'Cot du lieu thu 2
    With ActiveChart.SeriesCollection.NewSeries
        .Name = Kei(1) 'HaGiang
        .Values = A1 '= Array(300, 100, 1000)
    End With
    
    'Cot du lieu thu 3
    With ActiveChart.SeriesCollection.NewSeries
        .Name = Kei(2) 'HaiDuong
        .Values = A2 '= Array(2000, 800, 300)
    End With
    
    ActiveChart.HasLegend = True 'Hien thi chu giai
    ActiveChart.Legend.Position = xlLegendPositionBottom 'Vi tri phia duoi
    
    ActiveChart.HasTitle = True 'Hien thi title
    ActiveChart.ChartTitle.Text = "tuhocvba.net"
    
End Sub
Bạn cần đăng nhập để thấy đính kèm

Tham khảo :
 

tuhocvba

Administrator
Thành viên BQT
Thêm trục tung vào đồ thị:
Ở dữ liệu trên nếu ta thay đổi mảng A2 thành:A2 = Array(1, 2, 3) 'HaiDuong, như thế thì đồ thị hiển thị ra sẽ rất xấu.
Bạn cần đăng nhập để thấy đính kèm

Ta sẽ chèn thêm một trung tung nữa như sau:
Mã:
A2 = Array(1, 2, 3) 'HaiDuong
   
    'Add new graph
    ActiveSheet.Shapes.AddChart2.Select
    Set chrt = ActiveChart
    ActiveChart.ChartType = xlColumnClustered 'Type Bar
   
    'Cot du lieu thu nhat
    With chrt.SeriesCollection.NewSeries
        .XValues = X '= Array("Chuoi", "Cam", "Vai")
        .Name = Kei(0) 'HungYen
        .Values = A0 '= Array(1000, 400, 200)
        .AxisGroup = 1
    End With
   
    'Cot du lieu thu 2
    With chrt.SeriesCollection.NewSeries
        .Name = Kei(1) 'HaGiang
        .Values = A1 '= Array(300, 100, 1000)
        .AxisGroup = 1
    End With
   
    'Cot du lieu thu 3
    With chrt.SeriesCollection.NewSeries
        .Name = Kei(2) 'HaiDuong
        .Values = A2 '= Array(2000, 800, 300)
        .AxisGroup = 2
    End With
Kết quả:
Bạn cần đăng nhập để thấy đính kèm

Nguồn tham khảo:
 
Top