excel-vba ActiveWorkbook与ThisWorkbook
示例
ActiveWorkbook并且ThisWorkbook有时会通过VBA的新用户交替使用没有完全了解每个目标涉及到,这可能会导致在运行时意外的行为。这两个对象都属于应用程序对象
该ActiveWorkbook对象引用执行时当前位于Excel应用程序对象的最顶层视图中的工作簿。(例如,在引用该对象时可以看到并与之交互的工作簿)
Sub ActiveWorkbookExample()'// Let's assume that 'Other Workbook.xlsx' has "Bar" written in A1.
ActiveWorkbook.ActiveSheet.Range("A1").Value = "Foo"
Debug.PrintActiveWorkbook.ActiveSheet.Range("A1").Value '// Prints "Foo"
Workbooks.Open("C:\Users\BloggsJ\Other Workbook.xlsx")
Debug.PrintActiveWorkbook.ActiveSheet.Range("A1").Value '// Prints "Bar"
Workbooks.Add1
Debug.PrintActiveWorkbook.ActiveSheet.Range("A1").Value '// 什么都不打印
End Sub
的ThisWorkbook对象是指其中的代码属于在正在执行它时的工作簿。
Sub ThisWorkbookExample()'// 让我们假设该代码与当前处于活动状态的工作簿相同
ActiveWorkbook.Sheet1.Range("A1").Value = "Foo"
Workbooks.Add1
ActiveWorkbook.ActiveSheet.Range("A1").Value = "Bar"
Debug.PrintActiveWorkbook.ActiveSheet.Range("A1").Value '// Prints "Bar"
Debug.PrintThisWorkbook.Sheet1.Range("A1").Value '// Prints "Foo"
End Sub
以上是 excel-vba ActiveWorkbook与ThisWorkbook 的全部内容, 来源链接: utcz.com/z/347073.html