vba VBA如何打开另一个工作簿?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24470351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:24:28  来源:igfitidea点击:

VBA how do i open another workbook?

excelvba

提问by user3457548

I am trying to open another workbook, using the code below

我正在尝试使用下面的代码打开另一个工作簿

Sheets("Range").Activate
   Range("A1").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Workbooks.Open ("AvgStdev.xlsm")

And it was working before, but now excel is prompting the file cant be found. Help please :/

以前也能用,现在excel提示找不到文件。请帮忙 :/

回答by L42

You can do what you want easily if you declare your variable as discussed HERE.
So if we are to apply it, you can open your workbook like this:

如果您按照此处讨论的方式声明变量,您可以轻松地做您想做的事。
因此,如果我们要应用它,您可以像这样打开您的工作簿:

    Dim wb As Workbook
    Dim myfilename As String

    myfilename = "C:\Users\Ayaz\Desktop\Analysis\AvgStdev.xlsm"
    '~~> open the workbook and pass it to workbook object variable
    Set wb = Workbooks.Open(myfilename) 

    '~~> More codes here

Now later in your code if you are saving the same file:

现在,如果您要保存相同的文件,请稍后在您的代码中:

    wb.Save '~~> save
    wb.Close '~~> close

Or you can do it using Closemethod only:

或者你可以只使用Close方法来做到这一点:

    wb.Close True '~~> explicit SaveChanges argument to true

Now if however you like to save it as another file:

现在,如果您想将其另存为另一个文件:

    Dim newfilename As String
    newfilename = "C:\Users\Ayaz\Desktop\Analysis\Another.xlsm"
    '~~> If you are saving it in a format other than .xlsx,
    '~~> you have to be explicit in the FileFormat argument
    wb.SaveAs newfilename, xlOpenXMLWorkbookMacroEnabled
    wb.Close

HTH.

哈。

回答by tmit

Right click on your excel file and obtain the filepath from the properties, then substitute the actual filepath into the below:

右键单击您的 excel 文件并从属性中获取文件路径,然后将实际文件路径替换为以下内容:

Workbooks.Open ("filepath\AvgStdev.xlsm")