2017-06-21 154 views
-1

我正在编写一个代码,它可以跨选定工作表循环范围,以便为选定范围中的每个单元格的值乘以值,并在每个单元格上添加注释,但添加注释时会失败对选定工作表中各范围内的每个单元格发表评论。该错误是1004运行时错误。有人知道这里发生了什么吗?我已经完成了对互联网和论坛的研究,但找不到任何答案。嵌套循环if语句中addcomment的运行时错误

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 
+0

将错误的行(“else”语句之后的行)分解为单个逻辑步骤。逐一检查每个逻辑步骤,并检查所有正在使用的值。找到引发错误的确切步骤。用您的发现更新您的问题。 –

+0

嗨,大卫,它发生,即使当我使用简单的代码: MyCell.AddComment“A”,我认为问题发生时,我尝试通过范围跨越工作表使用addcomment方法。 –

+0

我明白了。在[官方文档](https://msdn.microsoft.com/VBA/Excel-VBA/articles/range-addcomment-method-excel)中获取一个掠夺并尝试该示例。如果可以使其工作,请进行更新。 –

回答

0

尝试这种方式

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

嗨Maddy Nikam,它停止并弹出错误1004在MyCell.Addcomment行,这是我的代码相同的东西。 –

0

MS documentation试试这个代码:

Worksheets(1).Range("E5").AddComment "Current Sales" 

如果一切正常,你可以从那里您的方式工作。

+1

刚发现你不能在每个循环内嵌套使用addcomment方法,但是你可以为每个循环使用一个。我认为这可能是Mircrosoft VBA的一个缺陷 –