"方法'行'对象' _Global'失败"当第二次来自

时间:2017-11-03 15:58:04

标签: excel-vba vba excel

我有一个我正在工作的项目,它接受一个大型机生成的报告并对其进行解析,从大型机中提取额外信息并生成容量与负载报告。通过加载报告第一次运行时,一切正常。它创建一个新的工作簿,命名,保存,一切。我试图添加添加项目报告的功能,而无需修改大型机报告并重新解析整个事情。我正在调用完全相同的子和函数,但是当尝试将一个项添加到报表中并且它在代码中到达此行时它将失败。

Set xlcell = WB.Sheets(WCSheetName).Cells(WB.Sheets(WCSheetName).Cells(Rows.Count, "B").End(xlUp).Row + 1, "B")

此代码位于两个实例中从同一个sub调用的函数中。该函数定义为

Function AddToWC(ByVal WCSheetName As String, _
            ByVal WCName As String, _
            ByVal Cmpt As String, _
            ByVal Parent As String, _
            ByVal dDate As Date, _
            ByVal ReqHrs As Single, _
            ByVal WB As Workbook, _
            ByVal ID As String, _
            ByVal Seq As String, _
            ByVal Description As String, _
            ByVal Plt As String, _
            ByVal Que As Long) As Date

最好的我可以说,这应该可行,因为我已经对它应该引用的工作簿和工作表进行了限定

使用此代码行调用该函数

CDT = AddToWC("WC_Summary", rs!WCID, gProdStruct.Components(Y).Name, gProdStruct.Name, CDT, xlCell.Offset(0, 16).value - xlCell.Offset(0, 11).value, CPWB, RefID, rs!SeqNum, rs!OpDesc, rs!WCPlt, xlCell.Offset(0, 11).value)

工作簿已经过验证并以CPWB传递并设置为正确的工作簿,首先通过调用gCheckForWorkbook Plt, IsPList检查工作簿是否已打开,然后将其分配给CPWB使用此行Set CPWB = Application.Workbooks(gWBName)

这会运行此子并设置全局变量

Sub gCheckForWorkbook(ByVal Plt As String, Optional ByVal IsPList As Boolean)
    Dim WB As Workbook
    Dim WBE As Boolean
        For Each WB In Workbooks
            If InStr(1, WB.Name, "Capacity Planning Rep", vbTextCompare) > 0 Then
                If IsPList = False Then
                    If MsgBox("A Capacity Planning workbook is already open." & vbCrLf & "Would You Like To Use It?", vbYesNo) = vbYes Then
                        gWBName = WB.Name
                        WBE = True
                        Exit For
                    Else
                        MsgBox "Please Close The Open Workbook And Run The Report Again"
                        ' return value to exit sub
                        WBE = True
                        Exit For
                    End If
                Else
                    WBE = True
                End If
            End If
        Next WB
        If WBE = False Then gCreateWorkBook Plt
End Sub

1 个答案:

答案 0 :(得分:0)

看来,由于某种原因,代码行.Cells(Rows.Count, "B")的这一部分是造成我问题的确切部分。似乎Rows.Count仍然被认为是不合格的,当我从

更改它时
Set xlcell =WB.Sheets(WCSheetName).Cells(WB.Sheets(WCSheetName).Cells(Rows.Count, "B").End(xlUp).Row + 1, "B")

Set xlcell = WB.Sheets(WCSheetName).Cells(WB.Sheets(WCSheetName).Cells(​WB.Sheets(WCSheetNam‌​e).Rows.Count, "B").End(xlUp).Row + 1, "B")

它完美无缺