作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想通过以下功能打开并引用工作簿。只有函数会产生运行时错误“91”:在跳回主代码之前未设置对象变量或 block 变量。
当我将确切的代码(只是不是函数)放入我的主代码时,它可以完美地工作。
但是我不想在我的主代码中包含整个函数,因为我认为它是不必要的和丑陋的。
也许有人可以帮助我使我的代码更好,更易于理解!
已经谢谢你了!
这是我的主要子的相关部分:
Sub main_sub()
Dim WBtest As Workbook
Dim WBpath As String
WBpath = ThisWorkbook.Sheets("Control").Range("A6").Value 'read path
WBtest = openfile(WBpath) 'I call my function here
End Sub
Public Function openfile(path As String) As Workbook 'path is fullpath
Dim wb As Workbook
Dim alreadyopen As Boolean
For Each wb In Workbooks 'loop over all Workbooks
If wb.FullName = path Then 'check if file is already open
alreadyopen = True
Set openfile = wb
End If
Next wb
If alreadyopen = False Then
'file not yet opened --> open it
Set openfile = Workbooks.Open(path)
End If
'MsgBox openfile.name 'this returns the right name
End Function
Sub main_sub()
Dim WBtest As Workbook
Dim WBpath As String
Dim wb As Workbook 'for loop
Dim alreadyopen As Boolean
WBpath = ThisWorkbook.Sheets("Control").Range("A6").Value 'read path
For Each wb In Workbooks 'loop over all Workbooks
If wb.FullName = WBpath Then
alreadyopen = True
Set WBtest = wb
End If
Next wb
If alreadyopen = False Then
'file not yet opened --> open it
Set WBtest = Workbooks.Open(WBpath)
End If
End Sub
最佳答案
两种方法的不同之处在于,在第一种方法中,您忘记了 Set
少量。因此,解决方案:
Set WBtest = openfile(WBpath) 'I call my function here
关于vba - 函数 "openfile"返回工作簿以运行时错误 '91' 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17918975/
我是一名优秀的程序员,十分优秀!