【发布时间】:2018-07-24 22:53:39
【问题描述】:
我有一个带有一些 VBA 的 Excel 2003 电子表格(“Tune.xls”)。它总是因错误而失败:
运行时错误 1004 '应用程序定义或对象定义错误'
当我单击调试时,它会将我带到代码中的以下行:
DataImport.Range("J10").Value = FileName 'Copy path and filename to worksheet "Import Data"
还请查看整个代码如下:
'Ensure that all global (public) flags are initialized properly; they might have been
'changed before the user requested a data import.
Sub_Error = False
Changed_Model_1 = False
Changed_Model_2 = False
Plot_Model_1 = False
Plot_Model_2 = False
Updated_Model_1 = False
Updated_Model_2 = False
'Disable screen updating to avoid flicker when graph data is modified. Puting the focus away
'from the graph to worksheet "Data Import" speeds up the execution by a factor of about 4. This trick
'is ad hoc and I cannot explain why it works, but it does...
Application.ScreenUpdating = False
DataImport.Select
'Open window to select data file. If no file is opened, then the variable FileName will be false.
FileName = Application.GetOpenFilename("Text Files (*.txt; *.dat),*.txt;*.dat, Excel Files (*.xls),*.xls", , "Open Process Data File")
If FileName = False Then Exit Sub 'exit if no file was opened or cancel button selected
******DataImport.Range("J10").Value = FileName 'Copy path and filename to worksheet "Import Data"******
'Open data file as a workbook and use shortcut name "DataSheet" for worksheet containing data.
Workbooks.Open FileName:=FileName, updateLinks:=0 'does not update linked cells
Set DataSheet = ActiveWorkbook.ActiveSheet
Set DataBook = ActiveWorkbook 'use shortcut for Data workbook
'The data workbook might contain cells referencing a DDE link. This makes it hard to manipulate
'the cells. Therefore, the entire worksheet is copied and only the values are pasted back. This
'will essentially remove all the DDE references.
DataSheet.Cells.Select 'This selects all cells
Selection.Copy
Selection.PasteSpecial Paste:=xlValues
请有人帮我恢复这个工作吗?
【问题讨论】:
-
我将从使用
Option Explicit开始并正确声明您的变量。这种组合解决了一半的问题 -
@kinshore:什么时候失败?在打开时,在单元格更改时?
-
什么是数据导入?请用它们的类型声明所有变量。例如,我希望 FileName 是一个字符串,但我看到 If FileName = False
-
@kinshore:欢迎来到 Stack Overflow:请阅读 How to ask a good question,然后编辑您的问题并确保询问 good, clear, concise question,包括代码、预期行为以及问题所在...那么我们可以尝试提供帮助
-
您是否将 DataImport 声明为工作表?