2016-05-19 63 views
1

我想:
- 打開文件"perpetual.xlsx"
- 篩選器可以根據標準列
- 以另一列的總和,而在另一個在我原來的文件中輸入它柱。我的原始文件如下圖所示。
- 繼續步驟2的循環直到原始文件的最後一行。總和列

enter image description here這裏是我的代碼:

Private Sub CommandButton1_Click() 
Dim RowLast As Long 
Dim tempLast As Long 
tempLast = ThisWorkbook.Sheets("combine BOMs").Cells(Rows.Count, "B").End(xlUp).Row 
Dim perporig As Workbook 

'ThisWorkbook.Sheets("combine BOMs").Cells(1, 9).Value = here 
For i = 5 To tempLast 
    Set perporig = Workbooks.Open("\\Etnfps02\vol1\DATA\Inventory\Daily tracking\perpetual.xlsx", UpdateLinks:=False, ReadOnly:=True) 
    With perporig.Sheets("perpetual") 
     .AutoFilterMode = False 
     RowLast = .Cells(Rows.Count, "A").End(xlUp).Row 
     .Range("A3:J" & RowLast).AutoFilter field:=1, criteria:=Range("B" & i).Value 
     ThisWorkbook.Sheets("combine BOMs").Cells(i, 5).Value = Application.WorksheetFunction.Sum(Columns("H:H")) 
     .AutoFilterMode = False 
    End With 
    perporig.Close savechanges:=False 
    ThisWorkbook.Sheets("myperpetual").Activate 
Next i 
Cells(1, 9).Value = here 
End Sub 

的代碼只運行至第9行,即:設置perporig = ....之後,它停止的某些原因。文件「perpetual.xlsx」打開並且代碼停止。如果我刪除第6行中的撇號,則代碼似乎完全沒有運行。

編輯代碼: 謝謝您的建議。不知道把我的代碼放在哪裏,所以就是這樣。再次,代碼只運行到第7行,即:設置perporig = ....並在此之後由於某種原因停止。文件「perpetual.xlsx」打開並且代碼停止。如果我刪除第6行中的撇號,則代碼似乎完全沒有運行。請幫忙。

Private Sub CommandButton1_Click() 
Dim RowLast As Long 
Dim tempLast As Long 
tempLast = ThisWorkbook.Sheets("combine BOMs").Cells(Rows.Count, "B").End(xlUp).Row 
Dim perporig As Workbook 
'ThisWorkbook.Sheets("combine BOMs").Cells(1, 9).Value = "here" 
Set perporig = Workbooks.Open("\\Etnfps02\vol1\DATA\Inventory\Daily tracking\perpetual.xlsx", UpdateLinks:=False, ReadOnly:=True) 
For i = 5 To tempLast 
    With perporig.Sheets("perpetual") 
     .AutoFilterMode = False 
     RowLast = .Cells(Rows.Count, "A").End(xlUp).Row 
     .Range("A3:J" & RowLast).AutoFilter field:=1, criteria:=ThisWorkbook.Sheets("combine BOMs").Cells(i, 2).Value 
     ThisWorkbook.Sheets("combine BOMs").Cells(i, 5).Value = Application.WorksheetFunction.Sum(Range("H:H").SpecialCells(xlCellTypeVisible)) 
     .AutoFilterMode = False 
    End With 
Next 
perporig.Close savechanges:=False 
ThisWorkbook.Sheets("combine BOMs").Activate 
Cells(1, 9).Value = "here" 
End Sub 
+1

呦uare打開每行「perpetual.xlsx」,這是過分沉重的東西。在對象中打開應用程序並將其關閉出循環 –

+0

在循環結束時刪除「Next i」,只保留沒有'I'計數器的「Next」 –

+1

這也不是你的問題,但它會是,總和將忽略該行是否通過過濾器隱藏,並將其包含在輸出中。您需要查看小計()函數。或者遍歷各行並測試它是否隱藏並保留自己的總和。 –

回答

1

7號線不能運行的原因是因爲你還沒有定義'這裏'是什麼。如果你想在那個單元格中放置文本,你應該用=「here」結束這行,這樣這個值就是一個字符串。

正如其他評論者所說。您不應該在循環中打開工作簿。首先打開工作簿,然後在打開書(perporig)的情況下執行循環操作。

+0

剛剛意識到,我打開了另一個文件它有自己的代碼,可能會干擾。我關閉它,而不是它進入for循環,但它在第12行(自動過濾器行)提供了一個錯誤。我得到「應用程序定義或對象定義的錯誤。」 –

0

終於明白了,這是一個簡單的錯誤,除了其他人的建議,我有mentoend標準:=而不是標準1:=
愚蠢的錯誤。