excel - 打开文件和刷新数据连接的 VBA 语法错误

标签 excel vba

不知道这里发生了什么...在 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

最佳答案

Workbooks.Open 的语法是

表达式.Open(文件名、UpdateLinks、ReadOnly、格式、密码、WriteResPassword、IgnoreReadOnlyRecommended、起源、分隔符、可编辑、通知、转换器、AddToMru、本地、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/False1/True 那么您必须更改

Sub openBook(fileName As String, UpdtLink As Boolean, RdOnly As Boolean)

Sub openBook(fileName As String, UpdtLink As Variant, RdOnly As Variant)

评论跟进

is there anyway to also activate that workbook in the same line or would another line of code be required? – metsales 1 min ago

为什么要激活它?应尽可能避免 .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

关于excel - 打开文件和刷新数据连接的 VBA 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20226813/

相关文章:

vba - 我想删除最后一个单词中的粗体/斜体/下划线格式以继续正常书写

excel - 提取字符之间的数字并对它们进行排序

python - Access ODBC 出现 "Operating system is not presently configured"错误

json - 数组的大小 excel - json vba 解析器

vba - Excel中的强制日期格式

vba - Open.ics 与 Outlook 2013 一起阅读项目

excel - 如何在 VBA 中引用动态创建的控件?

excel - Excel csv 文件中的字符串 (123)

excel - 在创建新的 excel 文件之前检查文件名是否已经存在

matlab - 将 excel 图表导出为图片(通过自动化)