请让我解释一下我想做什么:
(1)我创建了一个Excel工作簿,一个人可以在其中编写流程的各个步骤。假设它是写在名为“进程A”的工作表上的。在每个步骤右侧的单元格中,人员可以指定该步骤是否需要圆形(用于连接器),菱形(用于决策)或矩形(用于处理步骤)。
(2)对于工作表“ Process A”中的每个步骤,我也有条件公式,指示要在另一个工作表上放置形状(左,上,宽,高)的位置(我们称其为“流程图A“)。如果您想尝试一下,我将列出坐标,如下所示: 左侧>连接器= 147;流程和决策= 49
WIDTH>连接器= 90;流程和决策= 286
形状的高度>连接器= 90;流程和决策= 210
箭头的高度>所有箭头= 60
TOP>(基于先前形状的顶部+先前形状的高度+箭头的长度进行的计算)例如,如果形状1是连接器,形状2是过程,则形状2从150开始(假设形状1的顶部从0 ... [0 + 90 + 60]
以下代码确实产生了所有形状,但是将它们全部堆叠在最高点零(0)。
Sub TestRun()
Dim ws1 As Worksheet
Set ws1 = Worksheets("Process A")
Dim LDS As Shape
Dim ws2 As Worksheet
Set ws2 = Worksheets("Sheet2")
Dim LEFT As Integer
Dim TOP As Integer
Dim WIDTH As Integer
Dim HEIGHT As Integer
Dim LRange As Range
For Each LRange In ws1.Range("T2:T23")
LEFT = LRange.Value
Next LRange
Dim TRange As Range
For Each TRange In ws1.Range("U2:U23")
TOP = TRange.Value
Next TRange
Dim WRange As Range
For Each WRange In ws1.Range("V2:V23")
WIDTH = WRange.Value
Next WRange
Dim HRange As Range
For Each HRange In ws1.Range("W2:W23")
HEIGHT = HRange.Value
Next HRange
Dim ShpRange As Range
For Each ShpRange In ws1.Range("D2:D23")
If ShpRange.Value = "Connector" Then
Set LDS = ws2.Shapes.AddShape(msoShapeFlowchartConnector, LEFT, TOP, WIDTH, HEIGHT)
ElseIf ShpRange.Value = "Process" Then
Set LDS = ws2.Shapes.AddShape(msoShapeFlowchartProcess, LEFT, TOP, WIDTH, HEIGHT)
ElseIf ShpRange.Value = "Decision" Then
Set LDS = ws2.Shapes.AddShape(msoShapeFlowchartDecision, LEFT, TOP, WIDTH, HEIGHT)
End If
Next ShpRange
End Sub
我尝试了以下代码放置方式的变化:
(1)列出“对于每个”语句及其条件。然后列出所有“下一个语句”。 (2)一起列出所有“ For Each”语句,然后列出所有条件语句,然后列出所有“ Next语句”。
在这些编辑之后运行宏时,我收到“编译错误:无效的下一控件变量引用”。
我是VBA的新手,已经尝试了很多事情来完成这项工作,但是我觉得自己一遍又一遍地碰壁。非常感谢您的帮助!预先谢谢你!
答案 0 :(得分:0)
您可以简化为一个For Each
循环,使用Offset
引用相对于您遍历范围的不同列。
例如,此代码循环遍历T2:T23
,然后以正偏移量引用U-W列,以负值引用D列。
使用Select Case
语句可简化对连接器,流程或决策的选择。
Option Explicit
Sub TestRun()
Dim ws1 As Worksheet: Set ws1 = Worksheets("Process A")
Dim ws2 As Worksheet: Set ws2 = Worksheets("Sheet2")
Dim LDS As Shape
Dim Left As Integer, Top As Integer, Width As Integer, Height As Integer
Dim rng As Range
For Each rng In ws1.Range("T2:T23")
Left = rng.Value
Top = rng.Offset(, 1).Value
Width = rng.Offset(, 2).Value
Height = rng.Offset(, 3).Value
Select Case rng.Offset(, -16).Value
Case "Connector"
Set LDS = ws2.Shapes.AddShape(msoShapeFlowchartConnector, Left, Top, Width, Height)
Case "Process"
Set LDS = ws2.Shapes.AddShape(msoShapeFlowchartProcess, Left, Top, Width, Height)
Case "Decision"
Set LDS = ws2.Shapes.AddShape(msoShapeFlowchartDecision, Left, Top, Width, Height)
End Select
Next rng
End Sub