从工作表单元格中的目录获取数据

时间:2017-11-15 01:46:32

标签: excel-vba vba excel

我有疑问我的代码无法从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

1 个答案:

答案 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:=FalseClose方法的命名参数SaveChanges设置为值False }。