见图:http://s12.postimg.org/ov8djtuh9/Capture.jpg
上下文:尝试在另一个工作簿中激活工作表(变量:cSheet),并从其他工作簿中复制的数据中粘贴数据。每当我尝试使用变量直接激活(即工作表(名称).Activate)或尝试使用变量定义工作表然后激活它时,我都会得到一个超出范围的下标错误。我还尝试过其他编码风格,使用" With Worksheet"等等,我的代码要长得多,但我重新开始,因为每次我修复一些东西,都会出现其他问题。所以,坚持基础。任何帮助将不胜感激。
Sub GenSumRep()
Dim AutoSR As Workbook
Dim asrSheet As Worksheet
Dim tempWB As Workbook
Dim dataWB As Workbook
Dim SecName As String
Dim oldcell As String
Dim nsName As String
Dim cSheet As Worksheet
Set AutoSR = ActiveWorkbook
Set asrSheet = AutoSR.ActiveSheet
For a = 3 To 10
SecName = asrSheet.Range("D" & a).Value
If SecName <> "" Then
Workbooks.Open Range("B" & a).Value
Set tempWB = ActiveWorkbook
'tempWB.Windows(1).Visible = False
AutoSR.Activate
Workbooks.Open Range("C" & a).Value
Set dataWB = ActiveWorkbook
'dataWB.Windows(1).Visible = False
AutoSR.Activate
'Copy paste data
For b = 24 To 29
oldcell = Range("C" & b).Value
If b = 24 Then
nsName = Trim(SecName) & " Data"
Set cSheet = tempWB.Sheets(nsName)
Else
nsName = asrSheet.Range("B" & b).Value
Set cSheet = tempWB.Sheets(nsName)
End If
'Copy
dataWB.Activate
Range(oldcell).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Paste
tempWB.Activate
cSheet.Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
b = b + 1
Next b
End If
a = a + 1
Next a
End Sub
答案 0 :(得分:4)
您只会出于以下原因收到该错误:您提供的名称在集合中不存在!
根据您的代码,有几个可能的原因:
nsName
变量包含隐藏的字符,即使它看起来正确也会使其不同。根据您的评论,似乎您正在查找错误的工作簿。检查这些下标错误的一个好方法是迭代集合并打印出其中包含的Names
。
Dim sht as Worksheet
For Each sht In tempWB.Sheets
Debug.Print sht.Name
Next sht
通常,希望摆脱对Select
和Activate
的调用,以便您不依赖于接口来获取对象。有关详细信息,请参阅this post about avoiding Select
and Activate
。
应用于您的代码的一个想法是直接分配工作簿而不使用ActiveWorkbook
:
Set tempWB = Workbooks.Open(asrSheet.Range("B" & a).Value)
Set dataWB = Workbooks.Open(asrSheet.Range("C" & a).Value)
而不是:
Workbooks.Open Range("B" & a).Value
Set tempWB = ActiveWorkbook
'tempWB.Windows(1).Visible = False
AutoSR.Activate
Workbooks.Open Range("C" & a).Value
Set dataWB = ActiveWorkbook
'dataWB.Windows(1).Visible = False