我正在研究一个将去我的工作簿,清理数据(添加列,更改单位等)的宏的宏。清理数据后没有问题,我试图在工作表上创建一个散点图。下面的代码留下了清理的东西,因为它是无关紧要的。我已经尝试了一些迭代,包括录制宏,这是我的最后一次尝试。原来来自不同excel文件的表单出现问题。每张纸都有相同的格式/组织结构,但是,它们每个都有不同的列长度(因为每个数据的长度取决于实验持续的时间长短)。有没有人有什么建议?Scatterplot w/VBA在Excel中的多个工作表
Sub Cleaning()
Application.ScreenUpdating = False
For Each sh In Worksheets
sh.Activate
'find column length for loop
Dim collength As Integer
collength = Cells(Rows.Count, "A").End(xlUp).Row
'plot curves
ActiveSheet.Shapes.AddChart2(240, xlXYScatter).Select
ActiveChart.SetSourceData Source:=Range(ActiveSheet.Name & "!$C$1:$C$" & collength, ActiveSheet.Name & "!$Q$1:$Q$" & collength)
Next sh
Application.ScreenUpdating = True
End Sub
在我的第二次尝试中,我尝试过......仍然没有运气。
Dim strx As String
Dim stry As String
Dim rngx As Range
Dim rngy As Range
strx = "=" & ActiveSheet.Name & "!$C$2:$C$" & collength
stry = "=" & ActiveSheet.Name & "!$Q$2:$Q$" & collength
Dim Chart1 As Chart
Set Chart1 = Charts.Add
With Chart1
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
'Change to what your series should be called
.SeriesCollection(1).Name = "=""Values"""
.SeriesCollection(1).XValues = "=" & rngx
.SeriesCollection(1).Values = "=" & rngy
End With
在我的第三次尝试,我记录一个宏并将其编辑成自动调整到活动工作表的列的长度,但是,我得到最后一行1004错误。
Sub plotting_test()
Application.ScreenUpdating = False
For Each sh In Worksheets
sh.Activate
'find column length for loop
Dim collength As Integer
collength = Cells(Rows.Count, "A").End(xlUp).Row
'[B3].Value = collength
Range("C1").Select
Range(Selection, Selection.End(xlDown)).Select
Range("B1:B" & collength & ",Q1").Select
Range("Q1").Activate
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Shapes.AddChart2(240, xlXYScatter).Select
ActiveChart.SetSourceData Source:=Range(_
ActiveSheet.Name & "!$B$1:$B$" & collength & "," & ActiveSheet.Name & "!$Q$1:$Q$" & collength)
Next sh
Application.ScreenUpdating = True
End Sub
参见[这](https://stackoverflow.com/questions/46594615/creating-a-scatter-plot-containing-series-dynamically-using-vba-in-microsoft-exc/46596948#46596948 ) –