我是VBA的新手。正在尝试为场景编写全局宏。情景是,
我有WorkBook1(WB1),这将是我的全球宏工作手册。
我有实际的工作簿(WB2),我在那里计算所有数据。
现在我想编写一个宏,它实际上可以将WB2中的单元格值初始化为WB1中的单元格。等式看起来像是,
WB1.sheet1.cell(2,1) = WB2.sheet7.cells(2,2) '--> (Sheet7 is a sheet in WB2)
我实际上是将WB2(B2)单元格的值初始化为WB1(A1)单元格。
我做错了什么?
答案 0 :(得分:0)
我建议你先在workbook2上计算所有内容,然后将所有值从workbook2粘贴到workbook1,这很容易吗?
答案 1 :(得分:0)
以下是一个完整的示例,其中我假设wb1
包含宏,wb2
将在现场打开:
Sub Example()
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open("SomePath\Somefile.xlsx")
'Set cell B2 on sheet7 in the data calculation workbook (somefile.xlsx) to be equal to the Macro workbook sheet 1 range A1.
wb2.Worksheets("Sheet7").Range("B2").Value = wb1.Worksheets("Sheet1").Range("A1").Value
'Or the other way around: Get a value from the calc wb into the macro wb:
wb1.Worksheets("Sheet1").Range("A1").Value = wb2.Worksheets("Sheet7").Range("B2").Value
End Sub
编辑:根据您的评论 - 当然您可以从某处获取工作簿路径,但是您需要打开工作簿才能使用内部的对象(工作表,单元格等)它的。
Sub Example()
Dim path as string
Dim wb1 As Workbook
Dim wb2 As Workbook
Set wb1 = ThisWorkbook
path = wb1.Worksheets("Sheet1").Range("A2").value 'Put "Somepath\Somefile.xlsx" without the quotes in this range.
Set wb2 = Workbooks.Open(path)
'Set cell B2 on sheet7 in the data calculation workbook (somefile.xlsx) to be equal to the Macro workbook sheet 1 range A1.
wb2.Worksheets("Sheet7").Range("B2").Value = wb1.Worksheets("Sheet1").Range("A1").Value
'Or the other way around: Get a value from the calc wb into the macro wb:
wb1.Worksheets("Sheet1").Range("A1").Value = wb2.Worksheets("Sheet7").Range("B2").Value
End Sub