我遇到了这个问题:
我正在使用VBA制作一些图表。
我创建了一些输入字段......这些输入字段通过按钮传输到表格,然后从该表格中绘制折线图。
看起来像这样:
D栏中的答案,它们都是可更改的,但数字是常数,总是12 ......
然后我拿到了桌子,按下按钮,答案转移到了:
点是,按钮点击,我向表中添加一个新行,最后一行(从S到AB)是通用数据,我用答案中的公式制作。
一旦我添加了新行,我还将时间戳添加到左侧......
现在,我准备制作一个折线图......最后4列是Y,Z,AA和AB 我做到了,但我不知道如何将时间戳添加到x轴上。
时间戳看起来像这样:
以下是我的按钮代码:
Sub AddData()
'
' AddData Macro
' Adds data to the table
'
' Keyboard Shortcut: Ctrl+d
'
Dim cellValue As Variant
Dim rowSize As Integer
Dim i As Integer
Dim myRange As Variant
Dim cell As Variant
Dim column_Position As Integer
Dim row_Position As Integer
Dim rangeFormula As Variant
rowSize = 12
row_Position = -1
Set myRange = range("G1:G1000")
'Find first empty row
For Each cell In myRange
If IsEmpty(cell.Value) Then
column_Position = cell.Column
row_Position = cell.row
Exit For
End If
Next cell
'Do for loop and fill the cells from G(7) to R(18) with data
For i = 1 To rowSize
cellValue = range("D2:D13").Cells(i).Value
range(Cells(row_Position, "G"), Cells(row_Position, "R")).Cells(i).Value = cellValue
Next i
'Copy formulas one row bellow, from S(19) to AB(28)
If row_Position > 4 Then
range(Cells(row_Position - 1, "S"), Cells(row_Position - 1, "AB")).Select
Selection.Copy
range(Cells(row_Position, "S"), Cells(row_Position, "AB")).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks _
:=False
End If
'Add timestamp to F cells
Cells(row_Position, "F") = Now()
Cells(row_Position, "F") = Format(Now(), "dd-mm-yyyy hh:mm:ss")
'Remove Selections
Cells(1, 1).Select
Application.CutCopyMode = False
'Delete all old charts
If Not Worksheets("Data").ChartObjects.Count = 0 Then
Worksheets("Data").ChartObjects.Delete
End If
'Draw a chart
Dim rng As range
Dim cht As ChartObject
'Your data range for the chart
Set rng = ActiveSheet.range(Cells(2, "Y"), Cells(row_Position, "AB"))
'Create a chart
Set cht = ActiveSheet.ChartObjects.Add( _
Left:=ActiveCell.Left, _
Width:=775, _
Top:=275, _
Height:=250)
'Populate chart with data
cht.Chart.SetSourceData Source:=rng
'Add gridlines
cht.Chart.Axes(xlCategory).HasMajorGridlines = True
'Determine the chart type
cht.Chart.ChartType = xlXYScatterLines
cht.Activate
cht.Chart.SeriesCollection(1).XValues = "=$F$4:$F$28"
End Sub
现在,我有这样的事情:
我用来制作图表的4行折线图。
但我不知道如何将F(F4到最后填充的行)列添加为x轴。
Edit1:忘记提及,一旦我将行添加到表中,当前图表将被删除,我创建一个新图表,其中包含所有数据,加上新行...
Edit2:感谢Pierre44,我将时间戳列向上移动了一行,并添加了一行,以便所有数组都具有相同的长度......它看起来像这样:
它差不多完成了,但是你能告诉我如何移动x轴,如图所示吗?
像这样:
感谢。
答案 0 :(得分:1)
一种可能的解决方案是从头开始定义图表的整个范围:
为此您可以替换:
Set rng = ActiveSheet.range(Cells(2, "Y"), Cells(row_Position, "AB"))
人:
Set rng = ActiveSheet.Range("Sheet1!$F$1:$F$" & row_Position & ",Sheet1!$Y$1:$AB$" & row_Position)
请注意,我将F4:F28更改为“F1:F”& row_Position,因为您需要在此处拥有与其他列中一样多的值
由于您的X值很长,您可能想要更改其方向 示例:
ActiveSheet.ChartObjects("Chart").Activate
ActiveChart.Axes(xlCategory).TickLabelPosition = xlLow