使用Chart 对象的ChartArea 属性。见下文:
Sub MoveChart()
Dim Sh As Worksheet: Set Sh = ThisWorkbook.Sheets("TraceTable")
Dim Shp As Chart
With Sh
Set Shp = .ChartObjects("EIT").Chart
Shp.ChartArea.Left = .Range("N2").Left
End With
End Sub
在任何情况下,您分离的宏都可以总结为一个宏,如下所示。
Sub FullRun()
Dim TSht As Worksheet
Dim LCol As Long, LRow As Long
Dim RoundOffR As Range, RoundOffC As Range
Dim ShotR As Range, ShotC As Range
Dim Cht As Chart
Dim DivideR As Range, DivideC As Range
Set TSht = ActiveWorkbook.Sheets("TraceTable")
With TSht
' Get boundaries.
LCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LRow = .Cells(.Rows.Count, 1).End(xlUp).Row
' Get top row and fill it with color.
With .Cells(1, 1).Resize(1, LCol)
.Interior.Color = 14136213
.Font.Bold = True
End With
' Use Union for a cleaner delete.
' Columns to delete are Date, Little, Deviation, F, G
Union(.Range("D:D"), .Range("F:F"), .Range("H:H"), .Range("O:P")).Delete
' Initialize the range to round off.
Set RoundOffR = .Range("E2:K" & LRow)
RoundOffR.NumberFormat = "0"
End With
' Round the values. If it's from E column, change from "0"
' format to "0.0000" format.
For Each RoundOffC In RoundOffR
RoundOffC.Value = Application.Round(RoundOffC.Value, 0)
If RoundOffC.Column = 11 Then
RoundOffC.NumberFormat = "0.0000"
End If
Next
' Insert new column, distribute some values
With TSht
With .Range("C1")
.EntireColumn.Insert
.Value = "Sample"
End With
.Range("E1").Value = "Type"
Set ShotR = .Range("D2:D" & LRow)
End With
For Each ShotC In ShotR
With ShotC
' Get the last two digits of D and put in E.
.Offset(0, 1).Value = Right(.Value, 2)
' Get the 10th position in D, get next two characters, and put in C.
.Offset(0, -1).Value = Right(.Value, 2)
' Get the last two digits in B, and replace D.
.Value = Right(.Offset(0, -2).Value, 2)
End With
Next
' Adjust formatting and create chart.
With TSht
.Cells.HorizontalAlignment = xlCenter
.Columns.AutoFit
.Rows.AutoFit
Set Cht = .Shapes.AddChart.Chart
End With
' Manipulate chart.
With Cht
.Parent.Name = "EIT"
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
With .SeriesCollection(1)
.XValues = TSht.Range("F2:F" & LRow)
.Values = TSht.Range("G2:G" & LRow)
End With
' User .ChartArea for size and position.
End With
' "Divide" the rows.
Set DivideR = TSht.Range("B2:B" & LRow)
For Each DivideC In DivideR
' If current cell is not empty and not equal to next cell, insert a row.
If Not IsEmpty(DivideC) And DivideC.Value <> DivideC.Offset(1, 0).Value Then
DivideC.Offset(1, 0).EntireRow.Insert
End If
Next
' Add borders.
TSht.Cells.SpecialCells(xlCellTypeConstants).Borders.LineStyle = xlContinuous
' Resize and move chart. Use .ChartArea for this.
With Cht.ChartArea
.Height = TSht.Range("N2:N14").Height
.Width = TSht.Range("N2:T2").Width
.Top = TSht.Range("N2").Top
.Left = TSht.Range("N2").Left
End With
End Sub
它负责处理从边框、列删除、分隔线、图表创建和操作等所有方面的工作。这是最好的,这样你的宏就不会到处乱跳。当然,它使用ActiveWorkbook,因此您可以将它放在另一个工作簿中,然后在突出显示包含TraceTable 工作表的工作簿时运行它。
希望这会有所帮助。