2016-08-22 112 views
0

我有一些我写的代码,并且遇到了特定行(Countifs语句)的问题。我以前从未在VBA中使用过,因此我认为它可能与Syntax有关?请有人看看,让我知道吗?VBA Countifs错误

非常感谢!

Sub TradeCopy() 

'Declare Variables 
Dim x As Worksheet 
Dim y As Worksheet 
Dim z As Range 
Dim FirstRow As Integer 
Dim LastRow As Long 
Dim i As Long 
Dim j As Long 
Dim s As String 
Dim t As String 
Dim count As Long 
Dim startdate As Long 

On Error GoTo ERROREND 

Application.DisplayAlerts = False 
Application.EnableEvents = False 

'Setting Values 
s = ActiveWorkbook.Sheets("Name Creator").Range("B4") 
Set x = ActiveWorkbook.Sheets(s) 

t = ActiveWorkbook.Sheets("Name Creator").Range("B5") 
Set y = ActiveWorkbook.Sheets(t) 

startdate = ActiveWorkbook.Sheets("Name Creator").Range("B3") 
'Find Cell where name occurs 
Set z = x.Columns("A").Find(what:="trade id", LookIn:=xlValues, Lookat:=xlWhole) 

'Return Start Row number 
FirstRow = z.Row + 1 
'Return Last Row number 
LastRow = x.Range("A" & Rows.count).End(xlUp).Row 
'Clear Existing Range of Values 
y.Rows(2 & ":" & Rows.count).ClearContents 

下面是给出问题的代码,特别是运行调试器时的“count =”行。

'Loop to highlight cells based on conditions 
For i = FirstRow To LastRow 
    count = Application.WorksheetFunction.CountIfs(x.Range("B:B"), x.Range(i, 2), x.Range("L:L"), "<" & startdate) 

休息的代码:

If (x.Cells(i, 21) = "Fra" Or x.Cells(i, 21) = "Swap" Or x.Cells(i, 21) = "Swaption" Or x.Cells(i, 21) = "BondOption" Or x.Cells(i, 21) = "CapFloor") And DateValue(x.Cells(i, 12).Value) > startdate And count <= 0 Then 
     x.Rows.Range("A" & i).Value.Interior.Color = vbRed 
    End If 
Next i 

'Loop to check for all 0 Cells and paste values 
For j = FirstRow To LastRow 
    If x.Cells(j, 1).Interior.Color = vbRed Then 
     x.Rows.Range("A" & j).Value = y.Rows.Range("A" & j).Value 
    End If 
Next j 

'Remove Duplicates 
y.Columns(2).RemoveDuplicates Columns:=Array(1) 

Application.DisplayAlerts = True 
Application.EnableEvents = True 

MsgBox ("All Done!") 

Exit Sub 

ERROREND: 
MsgBox ("Unexpected Error - Please Seek Assistance or Debug Code") 

End Sub 
+0

第一修改'LASTROW = x.Range(“A”&Rows.count).End(xlUp).Row '到'LastRow = x.Range(“A”&x.Rows.count).End(xlUp).Row'(不一定与您的错误有关,只是为了避免将来发生错误) –

+0

感谢您挑选那个 - 完成。 – Dames

+0

你仍然得到那个错误? –

回答

2

我认为你需要,下面来改变.Range.Cells

count = Application.WorksheetFunction.CountIfs(x.Range("B:B"), x.Range(i, 2), x.Range("L:L"), "<" & startdate) 

要:

count = Application.WorksheetFunction.CountIfs(x.Range("B:B"), x.Cells(i, 2), x.Range("L:L"), "<" & startdate) 
+0

谢谢,这个工作! – Dames

+0

很高兴我能帮到你 – neelsg