.net excel vba sum多页获取运行时错误1004:应用程序定义或对象定义错误

.net excel vba sum多页获取运行时错误1004:应用程序定义或对象定义错误,.net,vba,excel,sum,runtime-error,.net,Vba,Excel,Sum,Runtime Error,我在下面的代码中得到了这个1004运行时错误。我标记为注释的行是这个问题的关键。每当行标记为注释时,此代码总是出现1004运行时错误。当我把这行代码放回正常代码时,代码运行良好。在代码运行期间,是否可以跳过工作表激活,因为该激活会使excel在代码运行期间跳转 多谢各位 Public Sub Summary_calculation() Dim wb As Workbook Dim ws As Worksheet Dim endrow As Integer Dim tem

我在下面的代码中得到了这个1004运行时错误。我标记为注释的行是这个问题的关键。每当行标记为注释时,此代码总是出现1004运行时错误。当我把这行代码放回正常代码时,代码运行良好。在代码运行期间,是否可以跳过工作表激活,因为该激活会使excel在代码运行期间跳转

多谢各位

Public Sub Summary_calculation()

   Dim wb As Workbook
   Dim ws As Worksheet
   Dim endrow As Integer
   Dim temprow As Integer
   Dim tempcol As Integer
   Dim i As Integer
   Dim totalrec As Integer
   Dim tmpSheet As Worksheet
   Dim SKUCol As Integer
   Dim SKUName As String
   Dim tmpSheetrow As Integer
   Dim tmpcol As Integer
   Dim tmpQty As Double

   Set wb = ActiveWorkbook
   Set ws = wb.Sheets("Summary")

   SKUCol = 3

   totalrec = ws.Cells(startrow, 1).CurrentRegion.Rows.Count - 1

   For i = 1 To totalrec

      SKUName = ws.Cells(i + startrow, SKUCol).Value

      Set tmpSheet = wb.Sheets(SKUName)

      'tmpSheet.Activate (Got 1004 error whenever remove this line of code)

      tmpSheetrow = tmpSheet.Cells(startrow, Gapcol).CurrentRegion.Rows.Count + startrow - 1

      For tmpcol = 0 To 16
         With wb.Sheets(SKUName)

            ws.Cells(i + startrow, tmpcol + 4).Value = Application.WorksheetFunction.Sum(.Range(Cells(startrow + 1, PropStartcol + tmpcol), Cells(tmpSheetrow, PropStartcol + tmpcol)))

         End With
      Next tmpcol
      ws.Cells(1, 10) = Format(i / totalrec, "00%")
      DoEvents
   Next i

End Sub
你能试试吗

  • Set wb=ActiveWorkbook
    替换为
    Set wb=thishworkbook
  • 将代码放入新模块中
  • 此工作簿
    指执行代码的工作簿。 打开其他工作簿时,可能会发生错误1004。

    而不是此:

    ws.Cells(i + startrow, tmpcol + 4).Value = Application.WorksheetFunction.Sum(.Range(Cells(startrow + 1, PropStartcol + tmpcol), Cells(tmpSheetrow, PropStartcol + tmpcol)))
    
    写下:

    ws.Cells(i + startrow, tmpcol + 4).Value = Application.WorksheetFunction.Sum(.Range(.Cells(startrow + 1, PropStartcol + tmpcol), .Cells(tmpSheetrow, PropStartcol + tmpcol)))
    
    区别在于单元格前面的点(代码中有两次)。如果没有点,
    单元格
    将活动工作表或它们所在的工作表作为其工作表。它会中断,因为
    .Range()
    接受
    wb.Sheets(SKUName)

    这可能是StackOverflow中最常见的问题: