命名范围图VBA

时间:2019-01-24 08:35:53

标签: excel vba charts named-ranges

我试图制作多个先前创建的命名范围的图表,但是当引用包含命名范围名称的单元格时,我根本无法使VBA代码正常工作。

它看起来像这样:

Sub Top25_Charts()

Sheets("Top25Graphs").Activate
Set peerDataSht = ThisWorkbook.Worksheets("Top25History")
Set peerGraphSht = ThisWorkbook.Worksheets("Top25Graphs")
Set peerGraphDataSht = ThisWorkbook.Worksheets("Top25GraphsData")




Dim myDateRange As Range
'Dim myNamedRange As Range
Dim cht As Object
Dim NumberPeers As Integer
Dim NLetters As String
Dim NNumber As Integer


Application.ScreenUpdating = False


For i = 1 To 1


NumberPeers = peerDataSht.Cells(i + 30, 13)
NLetters = peerGraphDataSht .Cells(i + 30, 1)
CName = peerDataSht.Cells(i + 61, 2)
Set cht = peerGraphSht.Shapes.AddChart2.Chart
Set myDateRange = peerGraphDataSht.Range("Graph_Date")


With cht
.ChartType = xlXYScatterLinesNoMarkers
.HasTitle = True
.ChartTitle.Text = CName
.HasLegend = True
.Legend.Position = xlBottom


End With

For j = 1 To NumberPeers


NNumber = peerGraphDataSht .Cells(30, 1 + j)
num = peerDataSht.Cells(31, 1 + j)
PeerName = peerDataSht.Cells(61 + i, 1 + j)
'peerDataSht.Range(Cells(i + 30, 1 + j))
myNamedRange = NLetters & "_" & NNumber


With cht.SeriesCollection.NewSeries
.XValues = myDateRange
.Values = NLetters & "_" & NNumber
.Name = PeerName
End With

Next j


With cht.Parent
.Left = peerGraphSht.Range("B2").Left
.Top = peerGraphSht.Range("B2").Top
.Width = peerGraphSht.Range("B2:I2").Width
.Height = peerGraphSht.Range("B2:B16").Height
End With


Next i

Application.ScreenUpdating = True


End Sub

但是,我不能指代NLettersNNumber。两个引用NLettersNnumber包含命名范围,因此命名范围称为a_1a_2 .... z_6

peerDataSht.Range(Cells(i + 30, 1 + j))直接指向包含命名范围的单元格,但不能使用。

那么是否可以引用包含命名范围名称的单元格,还是我必须像在日期行Set myDateRange = peerGraphDataSht.Range("Graph_Date")中那样直接在代码中插入命名范围?我有151个命名范围,所以我不想这样做。

1 个答案:

答案 0 :(得分:0)

首先,我建议您在子例程上方添加Option explicit,因为这样可以防止代码中出现某些错字,例如peerGraphDataSht .Cells。它还可以防止未变暗的变量,例如myNamedRange

尝试进行dim myNamedRange as Range,然后将行myNamedRange = NLetters & "_" & NNumber更改为set myNamedRange = Range(NLetters & "_" & NNumber)。然后范围应满足您的需求。