Adding Axis Title in Excel with VBA

JL 41 Reputation points
2022-06-21T01:40:47.443+00:00

Hello there,

I am trying to make a Macro for adding X and Y-Axis tile in Excel with VBA. However, I noticed that it only allows me add title of X-Axis but not Y-Axis. Eventually, tile of X Axis will be replaced by Y. I am not sure what's wrong with it. The following is the code. Please help me figure out what is going on. Thanks in advance.

ActiveSheet.ChartObjects("Chart 2").Activate  
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleNone) ' clear out whatever it has  
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleNone) ' clear out whatever it has  
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)  
Selection.Caption = "X-Axis"  
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)  
Selection.Caption = "Y-Axis"
Developer technologies Visual Basic for Applications
Microsoft Security Microsoft Graph
0 comments No comments
{count} votes

Accepted answer
  1. kinuasa 371 Reputation points
    2022-06-21T04:12:38.257+00:00

    I suggest that using the Axis object as follows.

    Public Sub Sample()  
      With ActiveChart  
        With .Axes(xlCategory, xlPrimary)  
          .HasTitle = True  
          .AxisTitle.Text = "X"  
        End With  
        With .Axes(xlValue, xlPrimary)  
          .HasTitle = True  
          .AxisTitle.Text = "Y"  
        End With  
      End With  
    End Sub  
    
    3 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.