我正在编写一个宏以创建一个图形,在此图形中,您将几个数据文件组合在一起,选择希望x和y值位于第一组中的列,然后根据剩余长度来循环遍历其余列第一盘。但是,我收到此错误,告诉我添加对象chartobjects的方法失败。我不明白,因为此错误仅发生在某些文件上,而不发生在其他文件上。我的代码将对某些文件有效,但对其他文件无效。
Workbooks.Add
ActiveSheet.Name = "Test Results"
'Load CSV file
Cells.Select
Selection.Delete Shift:=xlUp
Selection.EntireColumn.Hidden = False
Selection.NumberFormat = "General"
Dim ws As Worksheet, strFile As Variant, x As Integer, y As Integer,
NumberOfFile As Integer, i As Integer, j As Integer
Dim LabelColumn As Integer, StartLine As Integer, WholeColumns As Integer,
LableColumnLetter As String, MaxColumn As String
Dim ExtraRows As Integer
'Variables
NumberOfFile = InputBox("How many files would you like to combine?")
Set ws = ActiveWorkbook.Sheets("Test Results") 'set to current worksheet
name
strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv",
MultiSelect:=True, Title:="Please select text file...")
For i = 0 To NumberOfFile - 1
With ws.QueryTables.Add(Connection:="TEXT;" & strFile(i + 1),
Destination:=ws.Cells(1, 1 + WholeColumns * i))
.PreserveFormatting = True
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
Next
LR = ActiveSheet.UsedRange.Rows.Count
StartLine = InputBox("Which row do the results start in?" & Chr(10)
& "i.e. The first row with numerical values.")
LastColumn = InputBox("What is the last column in the first set of data?"
& Chr(10) & "Note: Please input the column letters as numbers." & Chr(10)
& "i.e. a = 1 and c = 3.")
LastColumnL = InputBox("What is the last column in the first set of data?"
& Chr(10) & "Note: Please input the column as a letter rather than a
number.")
XColumn = InputBox("Which column contains your x values for your first set
of data?" & Chr(10) & "Note: This is case sensitive please use lowercase
letters.")
XColumn = Range(XColumn & 1).Column
YColumn = InputBox("Which column contains your y values for your first set
of data?" & Chr(10) & "Note: This is case sensitive please use lowercase
letters.")
YColumn = Range(YColumn & 1).Column
'Creating First Graph
Dim co As ChartObject
Dim ct As Chart
Dim sc1 As SeriesCollection
Dim ser1 As Series
'This is where the error occurs
Set co = ActiveWorkbook.Sheets("Test Results").ChartObjects.Add(Range
("B2").Left, Range("B2").Top, 400, 250)
co.Name = "Specimen 1"
Set ct = co.Chart
With ct
.HasLegend = True
.HasTitle = True
.ChartTitle.Text = "Specimen 1"
Set sc1 = .SeriesCollection
Set ser1 = sc1.NewSeries
With ser1
.Name = "Specimen " & Counter
.XValues = Range(Cells(StartLine, XColumn), Cells(LR, XColumn))
.Values = Range(Cells(StartLine, YColumn), Cells(LR, YColumn))
.ChartType = xlXYScatter
End With
End With
ActiveSheet.ChartObjects("Specimen 1").Activate
With ActiveChart
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).HasTitle = True
.SetElement (msoElementPrimaryValueGridLinesMinorMajor)
.SetElement (msoElementPrimaryCategoryGridLinesMinorMajor)
End With