在转到另一张纸之前closures当前纸张

我交换两张纸时出现错误。 我打开一个工作表并在其中粘贴一些数据,然后调用一个打开另一个工作表的函数。但是当我再次粘贴第一个工作表中的数据时,会抛出错误。

For y = 1 To size Set src = Workbooks.Open("C:Template\Mapping.xlsx") Worksheets("Sheet1").Activate Worksheets("Sheet1").Range("B" & rowCntr).Value = "abc" newValue= getNewValue() rowCntr=rowCntr+1 Next public Function getNewValue() Dim newV=123 Set src = Workbooks.Open("C:Template\Mapping - Development v1.0.xlsx") getNewValue=newV End Function 

它第一次正常工作,但在调用函数getNewValue()它将在Worksheets(“Sheet1”)中引发错误“下标超出范围”。Range(“B”&rowCntr).Value =“abc”line。

请帮忙。

您的代码示例不完整。 值得注意的是,它没有定义src是什么,但是这正是错误所在:我必须假定src是一个全局variables,并且在主函数和函数getNewValue中都设置了src

getNewValue返回时, src现在指向其他范围不存在的工作簿。

此外,我不确定一次又一次地打开工作簿是否会导致重新加载,重置或打开多个副本。 我build议你只打开一次,例如:

 Dim src as Object Dim src2 As Object Function main (size As Integer) Dim y As Integer Dim rowCntr As Integer Set src = Workbooks.Open("C:Template\Mapping.xlsx") Set src2 = Workbooks.Open("C:Template\Mapping - Development v1.0.xlsx") For y = 1 To size src.Worksheets("Sheet1").Activate src.Worksheets("Sheet1").Range("B" & rowCntr).Value = "abc" newValue= getNewValue() rowCntr=rowCntr+1 Next End Function Public Function getNewValue() Dim newV newV = 123 '...whatever you want to do... getNewValue = newV End Function 

不需要select/激活,而是使用对象(工作簿,范围)引用,如下所示

 Set src = Workbooks.Open("C:Template\Mapping.xlsx") '<~~ open workbook outside the loop since it doesn't depend on it For y = 1 To size src.Worksheets("Sheet1").Range("B" & rowCntr).Value = "abc" '<~~ use "src" workbook reference to point to it whatever may be the currently active workbook newValue= getNewValue() rowCntr=rowCntr+1 Next