2014-09-28 27 views
0

我遇到以下宏的問題。我試圖獲得以下在VBA中轉換的函數。將excel工作表功能轉換爲vba

=SUMPRODUCT(time!$I$1418:time!$I$39433,--(time!$E$1418:time!$E$39433=$B11),--(time!$G$1418:time!$G$39433=E$2)) 

這是因爲如果函數存在於太多的單元格中,該函數太慢會降低Excel。

這是我到目前爲止。我試圖從列c循環到第二行=「總計」的列,然後我沿着下一行,重複該過程,直到列B中的單元格爲空。

我有一個運行時錯誤1004,應用程序定義的錯誤或對象定義的錯誤,他們突出顯示sumproduct部分。

Sub date_stats() 

Dim first_cell As Integer 
Dim time As Worksheet 
Set time = ActiveWorkbook.Sheets("time") 
Dim i As Integer, j As Integer, num As Integer 

firstcell = Range("e65000").End(xlUp).Row + 1 

Do Until ActiveSheet.Range("b" & firstcell).Value = "" 
firstcell = firstcell + 1 
i = 2 
    Do Until ActiveSheet.Cells(2, i).Value = "total" 
    i = i + 1 

    num = Application.WorksheetFunction.SumProduct(time.Range("i2:i50000"), --(time.Range("E2:E50000") = ActiveSheet.Range("B" & first_cell)), --(time.Range("G2:G50000") = ActiveSheet.Cells(i, 2))) 

    Loop 
Loop 

第一次更新

我在進步。我忘了我正在使用一個不同的模塊,因此沒有將這些選項明確地放在新模塊上,而且我的拼寫錯誤firstcell和first_cell。我已經在VBA上刪除了所有的錯誤,但現在出現的結果是#REF,這意味着它引用了已刪除的單元格,顯然不是這種情況。這是新的更新工作簿。

https://drive.google.com/file/d/0B9zzW6-3m2qGeFNCdEhtem44Wnc/edit?usp=sharing

這裏是代碼:

Sub date_stats() 


Dim first_cell As Integer 
Dim time2 As Worksheet 
Set time2 = ActiveWorkbook.Sheets("time") 
Dim i As Integer, j As Integer, num As Integer 
Dim x As String 
Dim y As String 
Dim z As Range 




'num = Format(num, "standard") 


Application.ScreenUpdating = False 


With ActiveSheet 
first_cell = .Range("e65000").End(xlUp).Row 


'=SUMPRODUCT(time!$I$1418:time!$I$39433,--(time!$E$1418:time!$E$39433=$B11),--(time!$G$1418:time!$G$39433=E$2)) 


Do Until .Range("b" & first_cell).Value = "" 
first_cell = first_cell + 1 
i = 3 
    Do Until .Cells(2, i).Value = "total" 

    x = .Range("B" & first_cell).Address 
    y = .Cells(2, i).Address 
    Set z = .Cells(first_cell, i) 
    z.Value = Evaluate("=SUMPRODUCT(time2!$I$2:$I$50000,--(time2!$E$2:time2!$E$50000=" & x & "),--(time2!$G$2:time2!$G$50000=" & y & "))") 
    i = i + 1 
    Loop 
Loop 


End With 


Application.ScreenUpdating = True 




End Sub 
+0

嘗試使用'Application.ScreenUpdating = False'和'Application.ScreenUpdating = True'包圍您的宏的計算 – 2014-09-28 02:28:57

+0

這沒有幫助。 – user147178 2014-09-28 03:21:36

+0

將問題分解成更簡單的組成部分,直到您找出問題爲止。當然,確保VBA在模塊的頂部用'Option Explicit'編譯。 – Smandoli 2014-09-28 03:37:23

回答

0

問題解決了。我將工作表的名稱更改爲time2,因爲Excel已經將時間用作特殊功能。但是當我使用不再需要的評估功能時。

評估( 「= SUMPRODUCT(時間$ I $ 2:$ I $ 50000, - (時間$ E $ 2:$ E $ 50000 =」 & X &「), - (時間$ G $ 2:$! G $ 50000 =「& y &」))「)

所以這個問題是由於一個錯字。