Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 在范围内的单元格上迭代时出现类型不匹配错误_Vba_Excel - Fatal编程技术网

Vba 在范围内的单元格上迭代时出现类型不匹配错误

Vba 在范围内的单元格上迭代时出现类型不匹配错误,vba,excel,Vba,Excel,您好,我正试图在我的电子表格上运行以下vb代码,但我在运行过程中遇到一个错误,即数据类型不匹配。我只是想锁定值为0的单元格。有些单元格带有#NA值有什么想法吗 Sub Test() Dim Cell As Range Set MyPlage = Range("J6:J1074") For Each Cell In MyPlage.Cells If Not IsError(Cell) Then If Range("J6:J1074").Value = "0" Then

您好,我正试图在我的电子表格上运行以下vb代码,但我在运行过程中遇到一个错误,即数据类型不匹配。我只是想锁定值为0的单元格。有些单元格带有#NA值有什么想法吗

Sub Test()
Dim Cell As Range
Set MyPlage = Range("J6:J1074")
For Each Cell In MyPlage.Cells
    If Not IsError(Cell) Then
        If Range("J6:J1074").Value = "0" Then
       Range("J6:J1074").Locked = True
        End If


    End If

Next
End Sub
试试这个:

Sub Test()
    Dim Cell As Range
    Dim MyPlage As Range

    With ThisWorkbook.ActiveSheet
        .Unprotect
        .Cells.Locked = False
        Set MyPlage = .Range("J6:J1074")
        For Each Cell In MyPlage
            If Not IsError(Cell) Then
                If Cell.Value = "0" Then
                    Cell.Locked = True
                End If
            End If
        Next
        .Protect
    End With

End Sub

顺便说一句,最好将
ActiveSheet
更改为
工作表(“SheetName”)

+1:这会起作用,但最好指出,除非工作表受到保护,否则锁定单元格不会起作用。不过,希望OP知道这一点。谢谢,当我运行宏时,没有任何事情发生,单元格也没有被锁定?@user1342164:正如我指出的,请查看我的评论。你必须保护床单才能将其锁定。突出显示范围内任何
0
值的单元格,然后按
Ctrl-1
。转到
保护
选项卡。您将看到选中了
Locked
,但有一个警告。@user1342164,请参见上面的注释。对。你需要保护床单。我已经更新了答案谢谢,问题是我希望他们能够修改其他单元格。如果“我的单元格”包含值“$100”,则现在无法修改?提示:当您在范围内的单元格上进行迭代时,应该检查正在迭代的当前目标,而不是整个范围。见@simoco的答案。注意他是如何使用Cell.Value而不是整个范围的。:)