以下代码返回错误1004

时间:2015-07-20 17:22:33

标签: excel vba selection worksheet

我正在尝试使用代码上的工作表名称来选择范围。我有37张,我不想写代码37次。

Sub relatorio()
    Dim ws As Worksheet, GI As Integer, J As Integer
    J = 0
    For Each ws In ActiveWorkbook.Worksheets
        J = J + 1
        If ws.Name = "Brasil" Then
            i = (8 * 0) + 4 And GI = (13 * 0) + 271
        End If
        If ws.Name <> "Dados" Then

            'the error occur in the next line.
            Worksheets(ws.Name).Shapes.Range(Array("TRI")).Select
            Selection.Formula = "=Dados!a2"
            Selection.ShapeRange.TextFrame2.TextRange.Font.Name = "Calibri"
            Selection.ShapeRange.TextFrame2.TextRange.Font.Size = 9

        End If
    Next

End Sub

我不知道该怎么做

2 个答案:

答案 0 :(得分:0)

Worksheets(ws.Name).可以替换为ws. 离开你:

ws.Shapes.Range(Array("TRI")).Select

工作表上是否有一个名为“TRI”的形状,它出错了,或者工作表本身是隐藏的吗?

为了避免隐藏工作表的错误,并且为了避免必须选择每个形状,我建议:

with ws.Shapes.Range(Array("TRI")).Select
    .Formula = "=Dados!a2"
    .ShapeRange.TextFrame2.TextRange.Font.Name = "Calibri"
    .ShapeRange.TextFrame2.TextRange.Font.Size = 9
end with

答案 1 :(得分:0)

你的颂歌中有一些事情发生了。

首先,该行:

i = (8 * 0) + 4 And GI = (13 * 0) + 271

......很可能没有按照你的意图行事。它像现在一样成为孤立的布尔标准。如果您尝试将值分配给iGI,最好将其保留在两行上。

i = (8 * 0) + 4
GI = (13 * 0) + 271

接下来就是你对ws的使用。从Worksheet objectWorksheets collection分配到For Each...Next Statement后,您可以直接使用它。您不需要将其名称用作参考点。

Sub relatorio()
    Dim ws As Worksheet, GI As Integer, J As Integer
    J = 0
    For Each ws In ActiveWorkbook.Worksheets
        with ws
            J = J + 1
            If .Name = "Brasil" Then
                i = (8 * 0) + 4        'not at all clear what you are trying to do here
                GI = (13 * 0) + 271    'not at all clear what you are trying to do here
            End If
            If .Name <> "Dados" Then

                'the error occur in the next line.
                'the recorded code for selecting a shape object goes overboard; this is all you should require
                with .Shapes("TRI")
                    .Formula = "=Dados!a2"
                    .ShapeRange.TextFrame2.TextRange.Font.Name = "Calibri"
                    .ShapeRange.TextFrame2.TextRange.Font.Size = 9
                end with
            End If
        end with
    Next ws

End Sub