[英]VBA obtaining values from a workbook and put them in another workbook
I'm having trouble putting values from one workbook to another. 我无法将值从一个工作簿转移到另一个工作簿。
Right now it works, but as you can probably see in the code below, it constantly opens one workbook after the second one until the loop ends. 现在它可以工作了,但是正如您可能在下面的代码中看到的那样,它会在第二个工作簿之后不断打开一个工作簿,直到循环结束。 So my question: how can I do this without opening the workbooks all the time?
所以我的问题是:如何在不始终打开工作簿的情况下执行此操作?
Code: 码:
For i = 2 To LastRow
Set wb2 = Workbooks.Open("...")
With Worksheets("...")
x = .Cells(i, 2).Value
y = .Cells(i, 3).Value
End With
If variable1 = variable2 Then
Set wb = Workbooks.Open("...")
With Worksheets("...")
.Cells(i, 2).Value = x
.Cells(i, 3).Value = y
End With
End If
Next i
The following code gives me an error: Subscript out of range at x = wb2.WorkSheets("...").Cells(i, 2).Value
以下代码给我一个错误:
x = wb2.WorkSheets("...").Cells(i, 2).Value
标超出范围
Set wb2 = Workbooks.Open("...")
Set wb = Workbooks.Open("...")
For i = 2 To LastRow
x = wb2.WorkSheets("...").Cells(i, 2).Value
y = wb2.WorkSheets("...").Cells(i, 3).Value
If variable1 = variable2 Then
wb.WorkSheets("...").Cells(i, 2).Value = x
wb.WorkSheets("...").Cells(i, 3).Value = y
End If
Next i
How about like this, first set the wb
and wb2
objects outside the loop, and after just set the values directly between workbook. 怎么样,首先在循环外设置
wb
和wb2
对象,然后直接在工作簿之间设置值。
Set wb2 = Workbooks.Open("...")
Set wb = Workbooks.Open("...")
For i = 2 To LastRow
wb.Worksheets("...").Cells(i, 2).Value = wb2.Worksheets("...").Cells(i, 2).Value
wb.Worksheets("...").Cells(i, 3).Value = wb2.Worksheets("...").Cells(i, 3).Value
Next i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.