不确定这里发生了什么......在excel vba中创建一个子程序,打开并通过传递给它的值激活文件。显然我做错了什么......不知道是什么。
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
答案 0 :(得分:4)
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)
从评论中跟进
无论如何还要在同一行中激活该工作簿,还是需要另一行代码? - metsales 1分钟前
为什么要激活它?应尽可能避免.Activate
。您可能希望看到THIS
话虽如此,如果你想激活它,那么你必须使用像这样的代码
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
但是根据我之前关于不使用.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
答案 1 :(得分:0)
尝试这样的事情(未经测试)
Sub openBook(ByVal fileName As String, ByVal activate As Boolean)
Application.Workbooks.Open fileName:=filename
End Sub