打开文件和刷新数据连接的VBA语法错误
不知道这里发生了什么…在excel vba中创build一个子例程,打开并通过传递给它的值来激活文件。 显然我做错了什么…不知道是什么。
Sub openBook(ByVal fName As String, ByVal activate As Boolean) Application.Workbooks.Open(fName, 0, False) '= Required here? End Sub
编辑有工作,只是想检查,以确保这是正确的语法下面看到更新的代码:
Sub openBook(ByVal fileName As String, ByVal refresh As Boolean) Dim wb As Workbook Set wb = Workbooks.Open(fileName, 0, False) If refresh = True Then wb.RefreshAll End If End Sub
Workbooks.Open
的语法是
expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
这是你正在尝试?
Sub Sample() openBook "C:\MyFile.xlsx", False, True End Sub Sub openBook(fileName As String, UpdtLink As Boolean, RdOnly As Boolean) Application.Workbooks.Open fileName, UpdtLink, RdOnly End Sub
编辑
如果你想传递0/False
和1/True
那么你将不得不改变
Sub openBook(fileName As String, UpdtLink As Boolean, RdOnly As Boolean)
至
Sub openBook(fileName As String, UpdtLink As Variant, RdOnly As Variant)
跟随评论
反正也有激活该工作簿在同一行或将另一行代码是必需的? – 1分钟前的metsales
你为什么要激活它? 尽可能避免.Activate
。 你可能想看到这个
话虽如此,如果你想激活它,那么你必须使用这样的代码
Sub Sample() openBook "C:\MyFile.xlsx", False, True End Sub Sub openBook(fileName As String, UpdtLink As Boolean, RdOnly As Boolean) Dim wb As Workbook Set wb = Application.Workbooks.Open(fileName, UpdtLink, RdOnly) wb.Activate End Sub
但是,下面是我build议根据我以前的build议,不要使用.Activate
Dim wb As Workbook Sub Sample() openBook "C:\MyFile.xlsx", False, True DoEvents With wb ' '~~> Do something with the workbook here ' End With End Sub Sub openBook(fileName As String, UpdtLink As Boolean, RdOnly As Boolean) Set wb = Application.Workbooks.Open(fileName, UpdtLink, RdOnly) End Sub
尝试像这样(未经testing)
Sub openBook(ByVal fileName As String, ByVal activate As Boolean) Application.Workbooks.Open fileName:=filename End Sub