我有问题。我需要编写宏来选择E列中的值。 所选项目的值应介于单元格T2和U2中的值之间。 选择后,宏应绘制图表。
我尝试了3种方法:
第一种方法:
Sub wykres1()
Dim rng As Range
Dim cell As Range
Set rng = Range("E1", Range("E65536").End(xlUp))
For Each cell In rng
If cell.Value > "T2" and cell.value < "U2" Then Cell.Select
With Selection
ActiveSheet.Shapes.AddChart2
End With
Next cell
End Sub
Wykres1无效,因为带有
if
的行以红色突出显示。
第二种方法:
Sub wykres2()
Dim rng As Range
Dim cell As Range
Set rng = Range("E1", Range("E65536").End(xlUp))
For Each cell In rng
If cell.Value > ActiveSheet.Cell(2,20).Value and cell.value < ActiveSheet.Cell(2,21).Value Then Cell.Select
With Selection
ActiveSheet.Shapes.AddChart2
End With
Next cell
End Sub
Wykres2无效,因为带有
if
的行以红色突出显示。
第三种方法:
Sub wykres3()
Dim rng As Range
Dim cell As Range
Set rng = Range("E1", Range("E65536").End(xlUp))
For Each cell In rng
If cell.value > -35 And cell.value < -32 Then cell.Select
With Selection
ActiveSheet.Shapes.AddChart2
End With
Next cell
End Sub
Wykres3运行后冻结。当我用绘制图表删除零件时, 宏选择一个单元格而不是所选值的范围。在这里我 将值放在宏(-35)(-32)中-但我对可能性感兴趣 从单元格(T2)(U2)中放入值。
正如我提到的那样-我需要创建宏,以选择E列中单元格的值介于T2和U2单元格之间的值。选择宏后必须绘制图表。
谢谢您的帮助。
答案 0 :(得分:1)
尝试一下(未经测试)。避免使用.Select
。处理对象。您可能需要查看How to avoid using Select in Excel VBA
Sub wykres1()
Dim rng As Range, cell As Range
Dim lRow As Long, i As Long
Dim ws As Worksheet
'~~> Change as applicable
Set ws = Sheet1
With ws
'~~> Find last row in Col E
lRow = .Range("E" & .Rows.Count).End(xlUp).Row
'~~> Loop though the range
For i = 1 To lRow
If .Range("E" & i).Value > .Range("T2").Value And _
.Range("E" & i).Value < .Range("U2").Value Then
With .Range("E" & i)
'
'~~> Do Something
'
End With
End If
Next i
End With
End Sub
正如我提到的那样-我需要创建宏,以选择E列中单元格的值介于T2和U2单元格之间的值。选择宏后,必须绘制图表。
您可以将上面找到的每个范围存储在一个范围对象中,然后使用它。看到这个例子
Sub wykres1()
Dim rng As Range, cell As Range
Dim lRow As Long, i As Long
Dim ws As Worksheet
Dim Obj As ChartObject
'~~> Change as applicable
Set ws = Sheet1
With ws
'~~> Find last row
lRow = .Range("E" & .Rows.Count).End(xlUp).Row
'~~> Liip though the range
For i = 1 To lRow
If .Range("E" & i).Value > .Range("T2").Value And _
.Range("E" & i).Value < .Range("U2").Value Then
'~~> Store the cell in a range object
If rng Is Nothing Then
Set rng = .Range("E" & i)
Else
Set rng = Union(rng, .Range("E" & i))
End If
End If
Next i
'~~> Once you have the range, create a chart and assign range
If Not rng Is Nothing Then
With .ChartObjects.Add(Left:=100, Width:=375, Top:=75, Height:=225)
.Chart.SetSourceData Source:=rng
.Chart.ChartType = xlColumnClustered
End With
End If
End With
End Sub