我一直在为我的公司开发一个Excel宏,它打开几个工作簿,解析它们以获取特定的信息行,存储该行,然后一旦经过每个工作簿就设置了一个水平选择的单元格的值。两页之一的单个工作簿。我遇到的问题是在尝试选择我需要将数据放入的第二页时,我得到运行时错误1004.
这是代码;
Sub sortandinsert(listie As Variant)
'Takes in the data array and sorts it as it inserts it into the spreadsheet.
'Expects a 2 dimensional array.
Dim serialarray() As Variant
Dim listlen1 As Integer
Dim listlen2 As Integer
Dim listlen3 As Integer
Dim count1 As Integer
Dim count2 As Integer
Dim SSCcurrentrow As Integer
Dim DSCcurrentrow As Integer
Dim Colstart As Integer
Dim SSCcounter As Integer
Dim DSCcounter As Integer
Dim actbook As Workbook
Dim selectrange As range
Set actbook = ActiveWorkbook
SSCcounter = 0
DSCcounter = 0
Colstart = 1
SSCcurrentrow = 10
DSCcurrentrow = 10
serialarray = FindSerial(listie, serialarray)
listlen1 = findlength(serialarray)
For count = 0 To listlen1 - 1
MsgBox serialarray(count)
Next
With actbook
listlen2 = findlength(listie)
For count1 = 0 To listlen1 - 1
MsgBox "Current Serial is" & " " & serialarray(count1)
For count2 = 0 To listlen2 - 1
If contains(listie(count2), CStr(serialarray(count1))) Then
listlen3 = findlength(listie(count2))
If listie(count2)(0) = "SSC" Then
Set selectrange = Sheets("SSC").range(Cells(SSCcurrentrow + SSCcounter, Colstart), Cells(SSCcurrentrow + SSCcounter, Colstart + listlen3 - 1))
With selectrange
.Value = listie(count2)
End With
SSCcounter = SSCcounter + 1
ElseIf listie(count2)(0) = "DSC" Then
Set selectrange = Sheets("DSC").range(Cells(DSCcurrentrow + DSCcounter, Colstart), Cells(DSCcurrentrow + DSCcounter, Colstart + listlen3 - 1))
With selectrange
.Value = listie(count2)
End With
DSCcounter = DSCcounter + 1
End If
End If
Next
SSCcurrentrow = SSCcurrentrow + SSCcounter + 6
DSCcurrentrow = DSCcurrentrow + DSCcounter + 6
'SSCcounter = 0
'DSCcounter = 0
Next
End With
End Sub
出现错误的代码部分是;
Set selectrange = Sheets("DSC").range(Cells(DSCcurrentrow + DSCcounter, Colstart), Cells(DSCcurrentrow + DSCcounter, Colstart + listlen3 - 1))
With selectrange
.Value = listie(count2)
End With
在我打开新工作簿以放入所有数据的宏的开头,然后我打开并关闭包含数据的工作簿,然后返回到创建的新工作簿。在宏的过程中会定期发生节约。
我该怎么做才能解决此错误?
答案 0 :(得分:0)
Cells
会引用ActiveSheet
中的ActiveWorkbook
。这些对象可能未设置,它们可能不在Sheet DSC上。试试这个:
With actbook.Sheets("DSC")
Set selectrange = range(.Cells(DSCcurrentrow + DSCcounter, Colstart), .Cells(DSCcurrentrow + DSCcounter, Colstart + listlen3 - 1))
End With
或者,更可读的版本可能是
Set selectrange = actbook.Sheets("DSC").Cells(DSCcurrentrow + DSCcounter, Colstart)
Set selectrange = selectrange.resize(1, listlen)