[英]Excel VBA Chart
我需要在excel上創建許多圖表,因為我有很多數字集。 理想情況下,我想創建一個散點圖,並且我是新手,學習如何使用excel和VBA。
我想創建一個模板模塊代碼以生成散點圖,在這里我可以為彼此不相鄰的列或行選擇X和Y值。 此外,我希望能夠格式化繪圖的詳細信息-字體,大小等。
有人可以幫我創建一個簡單的模板嗎? 謝謝。
我已經嘗試過這樣做。 我本質上希望能夠多次使用此Macro,以便能夠以相同的格式生成許多散點圖,但每次都選擇不同的X和Y值。
我可以在此代碼中添加些什么,以便在運行它時提示我選擇所需的X和Y值?
Sub Macro8()
'
' Macro8 Macro
'
' Keyboard Shortcut: Ctrl+Shift+W
' Dim rng As Range
Set rng = Application.InputBox(prompt:="Sample", Type:=8)
ActiveSheet.Shapes.AddChart2(240, xlXYScatterLines).Select
ActiveChart.SetSourceData Source:=rng
End Sub
這有點粗糙且准備就緒,但顯示了一些想法。 抱歉,如果您通過此設備進入時有任何錯別字,並且您確實想實現更好的錯誤處理。
Option Explicit
Public Sub Test()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Data") 'change as appropriate
Application.ScreenUpdating = False
BuildChart ws, SelectRanges(ws)
Application.ScreenUpdating = True
End Sub
Private Function SelectRanges(ByRef ws As Worksheet) As Range
Dim rngX As Range
Dim rngY As Range
ws.Activate
Application.DisplayAlerts = False
On Error Resume Next
Set rngX = Application.InputBox("Please select X values. One column.", Type:=8)
If rngX Is Nothing Then GoTo InvalidSelection
Set rngY = Application.InputBox("Please select Y values. One column.", Type:=8)
If rngY Is Nothing Then GoTo InvalidSelection
If rngX.Columns.Count > 1 Or rngY.Columns.Count > 1 Then GoTo InvalidSelection
On Error GoTo 0
Set SelectRanges = Union(rngX, rngY)
Application.DisplayAlerts = True
Exit Function
InvalidSelection:
If rngX Is Nothing Or rngY Is Nothing Then
MsgBox "Please ensure you have selected both X and Y ranges."
ElseIf rngX.Rows.Count <> rngX.Rows.Count Then
MsgBox "Please ensure the same number of rows are selected for X and Y ranges"
ElseIf rngX.Columns.Count > 1 Or rngY.Columns.Count > 1 Then
MsgBox "Please ensure X range has only one column and Y range has only one column"
Else
MsgBox "Unspecified"
End If
Application.DisplayAlerts = True
End
End Function
Private Sub BuildChart(ByRef ws As Worksheet, ByRef unionRng As Range)
With ws.Shapes.AddChart2(240, xlXYScatter).Chart
.SetSourceData Source:=unionRng
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.