切换Y轴为对数刻度后水平网格线消失,如何用VBA添加?
问题:对数刻度下Y轴水平网格线消失的VBA修复方案
我需要将图表的Y轴设置为对数刻度,但设置完成后,指示Y轴刻度的水平网格线消失了。请问能否通过VBA实现添加这些网格线?
我使用以下代码设置对数刻度:
.Axes(xlValue).ScaleType = xlScaleLogarithmic .Axes(xlValue).LogBase = 2.7
图表状态说明
- 设置后图表:Y轴为对数刻度,但无水平网格线,仅显示折线与坐标轴
- 目标效果:保持Y轴对数刻度的同时,显示对应刻度的水平网格线(带水平网格线的折线图样式)
注意:仅切换到对数刻度时,水平网格线才会消失。
完整VBA代码
Dim dataSheet As Worksheet Set dataSheet = Sheets("cudfFactor") Dim CurrentChart As Chart Dim Subtitle As Variant Set CurrentChart = ActiveSheet.Shapes.AddChart2(227, xlLine).Chart Dim startRow As Integer Dim endRow As Integer startRow = 1 endRow = dataSheet.Range(dataSheet.Cells(2, 2), dataSheet.Cells(2, 2)).End(xlDown).Row With CurrentChart With .Parent .Width = 430 .Height = 290 .left = 500 .top = topD End With .ChartArea.ClearContents .ChartTitle.Text = "Accumulated Top Quintile Log Returns" Dim i As Integer For i = 1 To 6 .SeriesCollection.NewSeries .FullSeriesCollection(i).Name = dataSheet.Cells(startRow, i + 1) .FullSeriesCollection(i).XValues = dataSheet.Range(dataSheet.Cells(startRow + 1, 1), dataSheet.Cells(endRow, 1)) .FullSeriesCollection(i).Values = dataSheet.Range(dataSheet.Cells(startRow + 1, i + 1), dataSheet.Cells(endRow, i + 1)) Next i .SetElement (msoElementLegendBottom) .Axes(xlValue).MaximumScale = 300 .Axes(xlValue).MinimumScale = 80 .Axes(xlValue).ScaleType = xlScaleLogarithmic .Axes(xlValue).LogBase = 2.7 End With
解决方案
在设置对数刻度的代码后,添加显式启用Y轴主要水平网格线的代码即可恢复:
' 启用Y轴主要水平网格线 .Axes(xlValue).MajorGridlines.Format.Line.Visible = msoTrue ' 可选:自定义网格线样式(颜色、粗细) .Axes(xlValue).MajorGridlines.Format.Line.ForeColor.RGB = RGB(200, 200, 200) .Axes(xlValue).MajorGridlines.Format.Line.Weight = 0.5
将这段代码插入到现有代码的.Axes(xlValue).LogBase = 2.7之后,修改后的关键代码片段如下:
.Axes(xlValue).MaximumScale = 300 .Axes(xlValue).MinimumScale = 80 .Axes(xlValue).ScaleType = xlScaleLogarithmic .Axes(xlValue).LogBase = 2.7 ' 启用水平网格线 .Axes(xlValue).MajorGridlines.Format.Line.Visible = msoTrue
原因:当使用非10的自定义对数底数时,Excel默认会隐藏网格线,因此需要显式设置其可见性。
内容的提问来源于stack exchange,提问作者Mathias Nissen
相关产品推荐
相关产品推荐

