Excel 2007范围和单元格语法问题
我正在尝试编写一个循环,从主工作表的页面中获取每一行,并将每个放在相应的工作表中。 例如,工作表1上的行A1:A10将被复制并放置在工作表2上的A1:A10上。在工作表3上,A1:A10值将来自工作表一个值A2:A10。 但我的问题是,我无法find正确的语法循环使用范围和单元格function的循环。
我的代码:
'i is set to the first worksheet I am writting to 'wsCount is set to the last worksheet I want to write to For i = 2 To wsCount Worksheets(i).Activate 'This code shifts old information down so the most recent is always on top Worksheets(i).Range("A3:L262").Select Selection.Copy Worksheets(i).Range("A4").Select ActiveSheet.Paste 'This sets the first cell in the row to be the current date Worksheets(i).Range("A3").Value = Format(Now, "ddd, d mmmm yyyy") 'This is my problem, I am trying to set the range 'B3:L12 to the corresponding row in the main worksheet Worksheets(i).Range(Cells(3, 2), Cells(3, 12)).Value = Worksheets(1).Range(Cells(x, 2), Cells(x, 12)).Value Worksheets(i).Range("A1").Select x = x + 1 Next i
此错误会引发"Run-time error '1004': Application-defined or object-defined error"
我觉得我的语法是正确的,因为当我运行:
Worksheets(1).Range(Cells(10, 2), Cells(10, 12)).Value = "Test"
它运行良好, 但只有当工作表(1)被选中。 所以我知道我需要select第一个工作表来从中获取信息,到其他工作表或类似的东西。 我错过了什么? 这与我的“工作表(i).Activate”语句在循环的开始有关吗? 我是VBA新手,不确定Excel VBAmacros的权限。
在这个代码中:
Worksheets(1).Range(Cells(10, 2), Cells(10, 12)).Value = "Test"
Range
方法适用于Worksheets(1)
但Cells
方法适用于活动工作表。 该代码相当于:
Worksheets(1).Range(ActiveSheet.Cells(10, 2), ActiveSheet.Cells(10, 12)).Value = "Test"
如果你只是使用一个固定的引用,那么你可以使用带有string参数的Range
方法的版本:
Worksheets(1).Range("B10:L10")
如果你需要一个根据variables的值而变化的引用,那么你可以使用With ... End With
块:
With Worksheets(1) .Range(.Cells(x, 2), .Cells(x, 12)).Value End With
那里的不合格的引用以a开头.
请参阅With ... End With
块中指定的对象。
在你不工作的代码中,你需要在同一行中引用两个不同的工作表,所以With ... End With
是不够的。 使用variables来引用每个工作表可能是完成这个工作的最明确的方法。 在For ... Next
循环开始之前,声明两个工作表variables:
Dim wsFirst As Worksheet Dim wsCurr As Worksheet
然后去:
Set wsFirst = Worksheets(1) For i = 2 To wsCount Set wsCurr = Worksheets(i)
你的问题线然后变成:
wsCurr.Range(wsCurr.Cells(3, 2), wsCurr.Cells(3, 12)).Value = wsFirst.Range(wsFirst.Cells(x, 2), wsFirst.Cells(x, 12)).Value
您还应该分别用wsFirst
和wsCurr
replace其他对Worksheets(1)
和Worksheets(i)
的wsFirst
。
正如在问题的评论中指出的,你也可以删除所有的select和激活,这将使你的代码更有效率,并停止它依赖于代码运行时哪个表正好处于活动状态。
只需在For Next结构之前添加x=1
。
x=1 For i = 2 To wsCount (...)
代码运行时,它会尝试select单元格(0,2),但不存在行= 0(x = 0)。 我相信这个解决scheme。
只是改变
Worksheets(i).Range(Cells(3, 2), Cells(3, 12)).Value = Worksheets(1).Range(Cells(x, 2), Cells(x, 12)).Value
至
For Each cell In Worksheets(i).Range(Cells(3, 2), Cells(3, 12)) Worksheets(1).Cells(x, cell.Column).Value = cell.Value Next cell
并给x初始值