Excel VBA 图表

Excel VBA Chart

我需要在 excel 上创建很多图表,因为我有很多组数字。理想情况下,我想创建一个散点图,并且我是学习如何使用 excel 和 VBA 的新手。

我想创建一个模板模块代码来生成一个散点图,我可以在其中为不相邻的列或行选择 X 和 Y 值。此外,我希望能够格式化绘图的详细信息——字体、大小等。

有人可以帮我创建一个简单的模板吗?谢谢你。

我试过这样做。我基本上希望能够多次使用这个宏,以便能够生成许多具有相同格式的散点图,但每次 selecting 不同的 X 和 Y 值。

我可以向此代码添加什么,以便当我 运行 它提示我 select 所需的 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