较小的代码更改后无法删除命名范围

时间:2019-04-23 11:02:13

标签: excel vba

我最近将代码分为两部分,以停止自动输入日期,因为星期一,我们需要处理3天的数据

我所做的就是添加一个新子并重新定义变量-现在我无法删除命名范围

我的代码:

Option Explicit
Sub Import()

Dim ws As Worksheet, lastRowC As Long

Set ws = Worksheets("Report")
lastRowC = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row + 1 ' bottom populated cell of Column "C", plus 1

    With ws.QueryTables.Add(Connection:= _
            "TEXT;N:\Operations\001 Daily Management\Cemex\FMSQRY.CSV", Destination:= _
            ws.Cells(lastRowC, 3))
        .Name = "FMSQRY"
        ' etc
        ' etc
        .Refresh BackgroundQuery:=False
    End With

    With ActiveWorkbook
        .Connections("FMSQRY").Delete
        .Names("FMSQRY").Delete
    End With

End Sub




Sub TodaysDate()

Dim ws As Worksheet, lastRowC As Long, lastRowH As Long

Set ws = Worksheets("Report")

lastRowH = ws.Cells(ws.Rows.Count, 8).End(xlUp).Row + 1 ' bottom populated cell of Column "H", plus 1
lastRowC = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row ' bottom populated cell of Column "C"

    With ws.Range(ws.Cells(lastRowH, 8), ws.Cells(lastRowC, 8))
        .FormulaR1C1 = "=TODAY()"
        .Value = .Value
    End With

End Sub

因此与命名范围实际上没有任何关系

.Name = "FMSQRY"仍是我的范围,但是当.Names("FMSQRY").Delete出现时,出现1004错误

Named Range

Debug


答案:

With ActiveWorkbook
    .Connections("FMSQRY").Delete
    With ws
        .Names("FMSQRY").Delete
    End With
End With

3 个答案:

答案 0 :(得分:2)

我不确定为什么该代码不起作用。

但是,如果您编写如下所示的代码,那么它将起作用...

Dim nm As Name
For Each nm In ActiveWorkbook.Names
    If nm.Name = "FMSQRY" Then nm.Delete
Next nm

答案 1 :(得分:2)

您的姓名在工作表级别而不是工作簿级别。(您在不同的工作表上可以使用相同的名称)

如此:

ActiveWorkbook.Worksheets("Report").Names("FMSQRY").Delete

答案 2 :(得分:1)

请尝试以下不带.connections的代码:

Option Explicit

Sub test()

    With ThisWorkbook
        .Names("FMSQRY").Delete
    End With

End Sub