另一个工作簿中的 VBA 更改值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44824107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA change value in another workbook
提问by Stan
I need some help changing variables in another workbook.
我需要一些帮助来更改另一个工作簿中的变量。
First I open the workbook with Workbooks.Open ("test.xlsx")
首先我打开工作簿 Workbooks.Open ("test.xlsx")
When I try to change a cell value with Workbooks("test.xlsx").Worksheets("Sheet").Cells(1, 1).Value = VariableX
it gives me error 9: subscript out of range. I don't see why it won't work. Can anyone help me out on this?
当我尝试使用Workbooks("test.xlsx").Worksheets("Sheet").Cells(1, 1).Value = VariableX
它更改单元格值时,会出现错误 9:下标超出范围。我不明白为什么它不起作用。任何人都可以帮我解决这个问题吗?
回答by jBuchholz
Workbooks.open
Returns a Workbook-object. Use this to reference the Workbook you want to manipulate:
Workbooks.open
返回一个工作簿对象。使用它来引用您要操作的工作簿:
dim wb as Workbook
set wb = Workbooks.Open("test.xlsx")
wb.Worksheets("Sheet").Cells(1,1).Value = variableX
' Close the workbook afterwards and save the changes
wb.Close True
回答by Gary's Student
Once you have Open
ed the workbook, it is Active
. Here is a small working example:
一旦你Open
编辑了工作簿,它就是Active
. 这是一个小的工作示例:
Sub Macro2()
Dim VariableX As Long
VariableX = 123
Workbooks.Open Filename:="C:\TestFolder\Book1.xlsx"
Worksheets("Sheet1").Cells(1, 1).Value = VariableX
ActiveWorkbook.Save
ActiveWorkbook.Close
End Sub