来自嵌套循环

时间:2017-06-21 06:52:05

标签: excel vba

我正在编写一个代码,可以在所选工作表中循环范围,使所选范围内每个单元格的值都倍,并在每个单元格上添加注释,但是当它在所选工作表的范围内向每个单元格添加注释时失败。错误是1004运行时错误。有谁知道这里发生了什么?我已经完成了互联网和论坛的研究,但无法找到答案。

Sub X2()

Dim MySheet As Worksheet 'For sheet in selected sheets
Dim MyCell As Range 'For cell in selected Ranges

If Selection.CountLarge > 1000 Then Exit Sub 'Avoid loop over 1000

If ActiveWindow.SelectedSheets.Count > 1 Then 'Range that across sheets

    For Each MySheet In ActiveWindow.SelectedSheets
        For Each MyCell In Range(Selection.Address)

            If Not MySheet.Range(MyCell.Address).Comment Is Nothing Then
                MySheet.Range(MyCell.Address).Comment.Text vbNewLine & Now & "_" & MySheet.Range(MyCell.Address).Value & "_" & Environ("Username") _
                , Len(MySheet.Range(MyCell.Address).Comment.Text) + 1 _
                , False
                'this program works fine
            Else

                MySheet.Range(MyCell.Address).AddComment Now & "_" & MySheet.Range(MyCell.Address).Value & "_" & Environ("Username")
                'Runtime Error 1004 for this code _
                i want to addcommet for each cell that _
                acoss sheets
            End If

            MySheet.Range(MyCell.Address).Comment.Shape.TextFrame.AutoSize = False

            MySheet.Range(MyCell.Address).Value = MySheet.Range(MyCell.Address).Value * 2

        Next MyCell
    Next MySheet

Else

    For Each MyCell In Selection
        If Not MyCell.Comment Is Nothing Then
            MyCell.Comment.Text vbNewLine & Now & "_" & MyCell.Value & "_" & Environ("Username") _
            , Len(MyCell.Comment.Text) + 1 _
            , False
        Else
            MyCell.AddComment Now & "_" & MyCell.Value & "_" & Environ("Username")
        End If

        MyCell.Comment.Shape.TextFrame.AutoSize = True

        MyCell.Value = MyCell.Value * 2
    Next MyCell

End If

2 个答案:

答案 0 :(得分:0)

试试这种方式

    MyCell.AddComment
    MyCell.Comment.Text Now & "_" & MyCell.value & "_" &  Environ("Username")

答案 1 :(得分:0)

尝试使用MS documentation

中的代码
Worksheets(1).Range("E5").AddComment "Current Sales"

如果有效,你可以从那里开始工作。