选择标题中带有#字符的表列时发生范围错误

时间:2018-08-24 21:27:57

标签: excel vba

我试图锁定许多类似构造的表中的某些列。日期和时间列将锁定。

当我尝试按构造方式锁定名称为“ [Phone#1]”的列时,它给我一个运行时错误1004,对象'_Global'的方法'Range'失败。

代码和屏幕截图包含在下面

Sub test()
' lockDesiredCellsInWeeklyTables
' This macro was made to lock certain columns in the weekly tables so that some less than technologically adept people wouldn't destroy the cells
Dim shtName As String
Dim tblName As String
Dim tbl As ListObject

shtName = "July"
tblName = "july"
dateName = "[Date]"
timeName = "[Time]"
phone1Name = "[Phone #1]"
phone2Name = "[Phone #2]"
phone3Name = "[Phone #3]"

ActiveSheet.Cells.Locked = False
For i = 1 To 4
    Set tbl = ActiveSheet.ListObjects(tblName & i)
    ' Locks the Date column
    Range(tbl & dateName).Select
    Selection.Locked = True
    Selection.FormulaHidden = True
    ' Locks the Time column
    Range(tbl & timeName).Select
    Selection.Locked = True
    Selection.FormulaHidden = True
    ' Locks the Phone #1 column
    Range(tbl & phone1Name).Select
    Selection.Locked = True
    Selection.FormulaHidden = True
    ' Locks the Phone #2 column
    Range(tbl & phone2Name).Select
    Selection.Locked = True
    Selection.FormulaHidden = True
    ' Locks the Phone #3 column
    Range(tbl & phone3Name).Select
    Selection.Locked = True
    Selection.FormulaHidden = True
Next i
ActiveSheet.Protect Password:="1234", DrawingObjects:=True, Contents:=True, Scenarios:=True _
    , AllowInsertingRows:=True, AllowDeletingRows:=True, AllowDeletingColumns:=False _
    , AllowSorting:=True, AllowInsertingColumns:=False, UserInterfaceOnly:=True

End Sub

链接到屏幕截图,因为我还不能发布图像 https://imgur.com/a/TGDoSoG

1 个答案:

答案 0 :(得分:0)

对于结构化引用,某些字符,例如#具有特殊含义,并且需要使用单引号(')作为转义字符。因此,您需要在每个#之前添加一个引号(')。 (Reference

phone1Name = "[Phone '#1]"
phone2Name = "[Phone '#2]"
phone3Name = "[Phone '#3]"

而且,正如urdearboy已经提到的那样,无需进行任何选择...

For i = 1 To 4
    Set tbl = ActiveSheet.ListObjects(tblName & i)
    ' Locks the Date column
    With Range(tbl & dateName)
        .Locked = True
        .FormulaHidden = True
    End With
    ' Locks the Time column
    With Range(tbl & timeName)
        .Locked = True
        .FormulaHidden = True
    End With
    ' Locks the Phone #1 column
    With Range(tbl & phone1Name)
        .Locked = True
        .FormulaHidden = True
    End With
    ' Locks the Phone #2 column
    With Range(tbl & phone2Name)
        .Locked = True
        .FormulaHidden = True
    End With
    ' Locks the Phone #3 column
    With Range(tbl & phone3Name)
        .Locked = True
        .FormulaHidden = True
    End With
Next i