4

我不明白为什么在尝试删除命名范围时不断收到“运行时错误'1004':应用程序定义或对象定义错误”消息。

这是用于从 .csv 文件导入数据并将范围命名为“历史”的代码

With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\<user name>\Downloads\history.csv", Destination:=Range(destCell))
    .Name = "history"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 3
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(3, 1, 2, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

这是用于删除“历史”命名范围的代码。请注意,紧接在它之前的行可以很好地找到命名范围。它只是不会删除名称。

Application.Goto Reference:="history"
ActiveWorkbook.Names("history").Delete
4

1 回答 1

5

答:问题是工作簿使用工作表名称作为命名范围的名称属性的一部分。具体来说,它使用 history!history 作为名称。

故障排除方法:我使用了在http://www.ozgrid.com/forum/showthread.php?t=49079&page=2上发布到类似问题的以下代码

Dim nameRng As Name 
Dim varVal As Variant 
On Error Resume Next 
For Each nameRng In ActiveWorkbook.Names 
    varVal = Range(nameRng.Name).Value 
    nameRng.Delete 
Next

VBA 编辑器中的 Locals 窗口显示该变量的 nameRng.Name 是字符串“history!history”。

修改后的代码:我删除了 Application.Goto Reference:="history" 行,因为它本质上是一个非功能性代码行(类似于 Select 操作),并将其作为删除导入范围名称的代码留下:

ActiveWorkbook.Names("history!history").Delete

平台:我在 Windows 7 Professional 上使用 Excel 2013

于 2014-08-19T22:29:48.333 回答