2016-11-26 91 views
0

我遇到了Excel VBA課程的程序問題。我已經編寫了一個程序,將每一行,矩形,橢圓和三角形添加到工作表中,這是btnAddShapes單擊事件。在cmdAlignRectangles單擊事件中,我試圖僅添加已添加的矩形並將它們全部對齊到C列中。我使用了For Each循環來選擇工作表中的所有形狀,分配需要For Each循環結構。然後我使用If/Then語句來選擇形狀類型msoShapeRectangle。當我使用計數器I遍歷每個矩形創建矩形(如「Box1」)時,我使用了我分配的名稱,正是這種說法給我一個錯誤,指出找不到具有該名稱的項目。我必須使用屬性的範圍形狀物體移動矩形。任何幫助或指導將不勝感激。將Excel VBA移動到列的形狀

Private Sub btnAddShapes_Click() 

Randomize 
For I = 1 To 5  
    ActiveSheet.Shapes.AddShape(msoShapeRectangle, 50, 100, 100, 65).Select 
    With Selection 
     .Name = "Box" & I 
     .Left = Int(422 * Rnd) 
     .Top = Int(422 * Rnd) 
    End With 

    ActiveSheet.Shapes.AddLine(10 + I * (Rnd * 133), 50 + I * (Rnd * 133), 125 + I * (Rnd * 133), 250 + I * (Rnd * 133)).Select 
    With Selection 
     .Name = "Line" & I 
    End With 

    ActiveSheet.Shapes.AddShape(msoShapeOval, 275, 240, 108, 44).Select 
    With Selection 
     .Name = "Oval" & I 
     .Left = Int(444 * Rnd) 
     .Top = Int(444 * Rnd) 
    End With 

    ActiveSheet.Shapes.AddShape(msoShapeIsoscelesTriangle, 514, 220, 93, 71).Select 
    With Selection 
     .Name = "Triangle" & I 
     .Left = Int(377 * Rnd) 
     .Top = Int(377 * Rnd) 
    End With 

Next I 
End Sub 

Private Sub btnRemoveShapes_Click() 
Dim sh As Shape 

For Each sh In ActiveSheet.Shapes 
    If Not (sh.Type = msoOLEControlObject Or sh.Type = msoFormControl Or sh.Type = msoTextBox) Then sh.Delete 
Next sh 

End Sub 

Private Sub cmdAlignRectangles_Click() 

Dim allRectangles As Shapes 
Dim sh As Shape 
Dim I As Integer 

Set allRectangles = ActiveSheet.Shapes 

I = 1 

For Each sh In allRectangles 
    If sh.Type = msoShapeRectangle Then 
     ActiveSheet.Shapes("Box" & I).Left = Cells(I, 3).Left 
    End If 
    I = I + 1 
Next 
End Sub 

回答

0

的錯誤是在創建循環創建4周的形狀爲每1,I會從1到5。另一方面,在對準環你迭代一個I爲每個形狀。因此,當我達到6(第六個形狀)時,名爲「Box6」的對象不存在。

一種更簡單的方式來實現,這將是通過檢查形狀的名字,像這樣修改我們的測試,例如:

If sh.Type = msoShapeRectangle And InStr(sh.Name, "Box") = 1 Then 
    sh.Left = Cells(I, 3).Left 
End If 

附:您還可以放棄測試的第一部分

+0

非常感謝您的幫助,我非常感謝! – codingYogi