Mik*_* PG 5 excel vba excel-vba excel-2010
我遇到了最奇怪的问题.我前几天在笔记本电脑上写了下面的代码,工作正常.现在,我正在我的桌面上测试它,它已停止工作.
首先,这是我的代码
Dim oApp As Application
Dim oWb As Workbook
Set oApp = New Application
oApp.Visible = True
Set oWb = oApp.Workbooks.Open(Filename:="C:\myFile.xlsx", ReadOnly:=True)
debug.print oWb.name
'returns "SOLVER.XLAM"
' "SOLVER.XLAM" is not "myFile.xlsx'
debug.print oApp.Workbooks.Count
'returns 1
debug.print oApp.Workbooks(1).name
'returns "myFile.xlsx"
现在,我知道解算器是一个插件,并且在创建它时会在新应用程序中加载...但是它如何执行此切换器?我仍然可以找到正确的文件,但我不想冒险在我的Application对象中只有一个文件(或者第一个文件是我加载的文件)的巧合
我正在调用从excel实例中执行这个宏,我希望打开一个单独的excel实例,然后"C:\myFile.xlsx"在另一个实例中打开特定的工作簿().
我遇到的关键问题是,当我打开另一个实例,然后添加工作簿并将其设置为我的oWb变量...不知何故,当我稍后调用该oWb变量时,它指的是与我设置的不同的东西至.
'This is how it makes me feel:
Dim x As Integer
x = 5
Debug.Print x
' 12
我认为,如果你只是稍微改进你的代码以确保你完全按照你想要的方式去做,那就没问题了。由于不清楚您是从 Excel 还是其他 MS Office 应用程序中调用代码,因此我将其放在下面的子目录中。
如果在 Excel 中运行,请运行以下命令:
Option Explicit
Sub insideXL()
Dim oWb As Workbook
Set oWb = Workbooks.Open("C:\myFile.xlsx", ReadOnly:=True)
Debug.Print oWb.Name
Debug.Print Workbooks.Count
Debug.Print Workbooks(1).Name
oWb.Close false
Set oWb = Nothing    
End Sub
如果在另一个程序中运行,请运行此命令。我使用早期绑定,但如果您愿意,也可以使用后期绑定:
Sub outsideXL()
'make sure Microsoft Excel X.X Object Library is checked in Tools > References
Dim oApp As Excel.Application
Set oApp = New Excel.Application
Dim oWb As Excel.Workbook
Set oWb = oApp.Workbooks.Open("C:\myFile.xlsx", ReadOnly:=True)
oApp.Visible = True
Debug.Print oWb.Name
Debug.Print Workbooks.Count
Debug.Print Workbooks(1).Name
oWb.Close = True
Set oWb = Nothing
Set oApp = Nothing    
End Sub
| 归档时间: | 
 | 
| 查看次数: | 3762 次 | 
| 最近记录: |