我有疑问我的代码无法从y = Workbooks.Open(源代码)运行。我想从单元格中读取目录,但它不起作用。为什么呢?
Sub Button4_Click()
Application.ScreenUpdating = False
Dim x As Workbook
Dim y As Workbook
Dim source As String
source = Cells(14, 6)
Set x = ActiveWorkbook
y = Workbooks.Open(source)
y.Sheets("Sheet1").Range("A:Z").Copy
Destination:=x.Sheets("Sheet3").Range("A:Z")
y.Close savechanges = False
End Sub
答案 0 :(得分:0)
您缺少设置对象引用所需的最重要的Set
关键字。所以
y = Workbooks.Open(source)
应该是
Set y = Workbooks.Open(source)
您的代码还有一些其他问题,可能看起来像:
Sub Button4_Click()
Application.ScreenUpdating = False
Dim x As Workbook
Dim y As Workbook
Dim source As String
'Note - this next line is using whatever worksheet is active in whichever
' workbook is active. This is potentially dangerous.
source = Cells(14, 6)
Set x = ActiveWorkbook
Set y = Workbooks.Open(source)
'You were missing a line continuation character on this statement
y.Sheets("Sheet1").Range("A:Z").Copy _
Destination:=x.Sheets("Sheet3").Range("A:Z")
'You were missing a colon in the named parameter of this statement
y.Close savechanges:= False
'You should reset ScreenUpdating
Application.ScreenUpdating = True
End Sub
:
中的savechanges:=False
重要吗?的是
您当前的代码y.Close savechanges = False
首先将名为savechanges
的变量的值与常量False
进行比较。由于您尚未声明该变量,也未为其指定值,因此savechanges
将被假定为数字零。因此,您正在执行测试0 = False
。由于VBA将零视为False
而-1视为True
,因此savechanges = False
将返回True
。这意味着你正在做相当于y.Close True
- 这几乎肯定与你的意图完全相反。
如果包含:
,则语法是SaveChanges:=False
将Close
方法的命名参数SaveChanges
设置为值False
}。