有時候屬性設定過長,打很多字很懶的時候,就可以用with ~ end with。
如下:
範例1:畫圖
Dim my_Range As Range
Dim my_Chart As ChartObject
Dim N As Integer
Dim xmin As Single, xmax As Single, ymin As Single, ymax As Single
Dim sj As String, X As String, Y As String, A As String, B As String
N = Application.CountA(Sheets("Sheet1").Range("A:A"))
xmin = Application.Min(Sheets("Sheet1").Range(A)) ' X最小值
xmax = Application.Max(Sheets("Sheet1").Range(A)) 'X最小值
ymin = Application.Min(Sheets("Sheet1").Range(B)) 'Y最小值
ymax = Application.Max(Sheets("Sheet1").Range(B)) 'Y最大值
Set my_Range = Sheets("Sheet1").Range("A" & 1 & ":B" & N) '設定my_Range 範圍
Set my_Chart = Sheets("Sheet1").ChartObjects.Add(100, 30, 400, 250) '設定my_Chart 為ChartObjects.ADD(範圍)
With my_Chart.Chart '透過WITH 可以省打很多字
.ChartType = xlXYScatterSmooth '散佈圖
.SetSourceData Source:=my_Range, PlotBy:=xlColumns
.HasTitle = True
.ChartTitle.Text = "TEST"
With .ChartTitle.Font '設定字型大小、顏色、字體
.Size = 16
.ColorIndex = 3
.Name = "標楷體"
End With
.ChartTitle.Text = "X資料序列"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = X
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = Y
With .Axes(xlCategory) '設定類別(xlCategory)座標軸格式的尺規最大最小值
.MinimumScale = xmin
.MaximumScale = xmax
End With
With .Axes(xlValue) '設定資料(xlValue)座標軸格式的尺規最大最小值
.MinimumScale = ymin
.MaximumScale = ymax
End With
With .ChartArea.Interior '設定圖表區的顏色
.ColorIndex = 15
.PatternColorIndex = 5
.Pattern = xlSolid '設定為純色
End With
With .PlotArea.Interior '設定繪圖區的顏色
.ColorIndex = 35
.PatternColorIndex = 1
.Pattern = xlSolid '設定為純色
End With
With .SeriesCollection(1) '設定第一個數列資料的格式
With .Border '框線
.ColorIndex = 3
.Weight = xlThin '線寬
.LineStyle = xlDot '框線形式
End With
.MarkerStyle = xlCircle '繪圖線形式
.Smooth = True '框線
.MarkerSize = 5 '繪圖線尺寸
End With
.Legend.Delete '刪除圖例
End With
Set my_Range = Nothing
Set my_Chart = Nothing
範例2:配合 Application.WorksheetFunction調用SUM函數
Dim a As Object
Set a = Sheets("工作表1").Range("a1:a100")
With a
Sheets("工作表1").Range("b1") = Application.WorksheetFunction.Sum(a) 'a已透過set設定為a1:a100的儲存格範圍
End With
沒有留言:
張貼留言