套用到
Mac 版 Microsoft 365 Excel Mac 版 Excel 2024 Mac 版 Excel 2021

下列 VBA (Visual Basic for Applications) 程式可讓您在 Mac 版 Excel 的圖表中使用單元格值做為數據標籤。 若要使用此程式,請執行下列動作:

  1. 在 Excel 中,按兩下 [ 巨集 > 工具]> [錄製新巨集]

  2. 在 [將 巨集儲存在:] 下拉式方塊中,選取 [個人巨集活頁簿]

    附註: 將 VBA 程式儲存在個人巨集活頁簿中,就可以在任何 Excel 實例中使用它。 這表示它不只是限制在單一活頁簿中使用。

  3. 按 [確定]。

  4. 移至 [巨集 ] > [ 工具]> [停止錄製]

  5. 移至 [巨集 > 工具]> Visual Basic 編輯器

  6. Visual Basic 編輯器 (VBE) 會在 Excel 上方開啟。 在左側的導航窗格中,展開 VBAProject (PERSONAL。XLSB) 資料夾以顯示 Module1

  7. 按兩下 Module1 以顯示程式 代碼窗格,該窗格會在 VBE視窗右側開啟。

  8. 不需要錄製新巨集時建立的 VBA 程序代碼,因此請選取全部,然後按 Delete。 

  9. 接下來,在下方文本框中選取 VBA 程式代碼,按 CMD+C 進行複製,然後以 CMD+V 將它貼回 [程序代碼] 窗格。 您現在可以結束 Visual Basic 編輯器 並返回 Excel。

  10. 建立含有數據標籤的圖表來測試巨集。 接下來,選取圖表上的任何數據標籤,然後按兩下 [巨集] > [工具] > [巨集] 來執行巨集。取 [SetCustomDataLabels],然後按 [執行]。 系統會自動提示您選取數據標籤範圍,因此請選取,然後按 [確定]。  

    附註: VBA 程式無法復原,因此請務必在活頁簿復本上試試看。 如果您確實執行程序代碼而不想保留結果,則必須關閉活頁簿而不儲存。

  11. 當您結束 Excel 時,請確定您選擇將變更儲存在個人版中。XLSB,以便日後提供巨集。

  12. 每當您想要新增或移除圖表中的數據標籤時,請選取數據標籤並執行巨集。

  13. 您可以使用 Excel > 喜好 設定> 功能區 & 工具列 新增按鈕,從功能區或工具列執行巨集。

VBA 程序

Option Explicit

Sub SetCustomDataLabels()
' make sure a series is selected
    If TypeOf Selection Is DataLabels Or TypeOf Selection Is Point Then
        Selection.Parent.Select
    ElseIf TypeOf Selection Is DataLabel Then
        Selection.Parent.Parent.Select
    End If

    If TypeOf Selection Is Series Then
        Else
        MsgBox "Select a chart series and try again."
        Exit Sub
    End If

    If Selection.HasDataLabels Then
        'If the data labels from cells are already showing, stop showing them and exit.
        'If labels include other info (e.g., values or categories) this will still appear
        If Selection.DataLabels.ShowRange Then
            Selection.DataLabels.ShowRange = False
            Exit Sub
        End If
    End If
 
'Use the InputBox dialog to set the range for the data labels
    On Error Resume Next
        Dim rng As Range
        Set rng = Application.InputBox(Prompt:="Select data label range.", Title:="Data Label Range", Type:=8)
    On Error GoTo 0

    If rng Is Nothing Then Exit Sub ' clicked cancel
        If Selection.HasDataLabels Then
            'This will include the new text from cells into existing data labels
        Else
        'Otherwise add data labels (empty labels)
            Selection.HasDataLabels = True
            Selection.DataLabels.ShowValue = False
        End If
    
    'Create a string that includes the sheet name and range reference.
    Dim rngAddress As String
        rngAddress = "='" & rng.Worksheet.Name & "'!" & rng.Address(RowAbsolute:=True, ColumnAbsolute:=True, External:=False)
        Selection.DataLabels.Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, rngAddress, 0
        Selection.DataLabels.ShowRange = True

End Sub

需要更多協助嗎?

您可以隨時詢問 Excel 技術社群中的專家,或在社群中取得支援。

需要更多協助嗎?

想要其他選項嗎?

探索訂閱權益、瀏覽訓練課程、瞭解如何保護您的裝置等等。