VBA CountIF不会计算整个列

时间:2018-08-16 16:27:07

标签: excel vba excel-vba worksheet-function countif

我正在创建VBA代码,该代码将允许用户将信息输入表单,然后将其移动到数据库中进行存储。在数据迁移期间,我尝试使用worksheetfunction.countif来防止将重复的“案例ID”输入数据库。当我尝试使用已知的重复项运行代码时,它仍然允许写入数据,并且似乎并没有计入整个列中。

我知道这个问题与其他几个已经提出的问题有关,但是我已经审查了我能找到的每个问题,在我看来,我在按照已经提供的答案进行操作。

有人可以告诉我为什么我的代码无法检测到A列中的重复项吗?

Sub DatabaseBuilder()

Dim CaseID As String
Dim CaseLevel As String
Dim Queries As String
Dim CaseReportData(2 To 8) As String
Dim UniqueIdentifier As String
Dim CaseCount As String


Worksheets("Case Reporting").Select
CaseID = Worksheets("Case Reporting").Cells(2, "D").Value
CaseLevel = Worksheets("Case Reporting").Cells(4, "D").Value
Queries = Worksheets("Case Reporting").Cells(1, "A").Value


For i = 2 To 4
    CaseReportData(i) = Worksheets("Case Reporting").Cells(i, 4).Value
Next i
For i = 5 To 7
    CaseReportData(i) = Worksheets("Case Reporting").Cells(i - 3, 8).Value
Next i
    CaseReportData(i) = Worksheets("Case Reporting").Cells(34, 3).Value



ReDim QueryData(1 To Queries) As String
Dim Count As Integer
Count = 1

For i = 1 To Queries
    UniqueIdentifier = Worksheets("Case Reporting").Cells(Count + 6, 3).Value
    If UniqueIdentifier = i Then
    QueryData(i) = Worksheets("Case Reporting").Cells(Count + 6, 6).Value
    Count = Count + 1
    End If
Next i


Set myData = Workbooks.Open....


Worksheets("Case Data").Select
Worksheets("Case Data").Range("A1").Select
RowCount = Worksheets("Case Data").Range("A1").CurrentRegion.Rows.Count
CaseCount = Application.WorksheetFunction.CountIf(Columns("A"), CaseID)
MsgBox CaseCount

If CaseCount < 1 Then
    For i = 2 To 8
        With Worksheets("Case Data").Range("A1")
        .Offset(RowCount, i - 2) = CaseReportData(i)
    End With

    Next i


    Worksheets("Case Data").Select
    Worksheets("Case Data").Range("H1").Select

    For i = 1 To Queries
        With Worksheets("Case Data").Range("H1")
        .Offset(RowCount, i - 1) = QueryData(i)
    End With
    Next i
End If


ActiveWorkbook.Save
ActiveWorkbook.Close


End Sub

1 个答案:

答案 0 :(得分:2)

我们实际上不需要看所有这些代码,原始帖子更好,大部分只是噪音。

无论如何,当前的问题可能是因为您对Column("A")使用了隐式引用。这意味着它可能不是Worksheets("Case Data"),而是活动工作簿中的当前工作表。

事实上,当您打开“数据库”文件时,活动工作簿会发生变化,我猜它也有一个名为“案例数据”的工作表,否则下一行会出错 < / strong>

您可以通过添加以下行来进行测试:

Debug.Print Columns("A").Parent.Name 

甚至

Debug.Print Worksheets("Case Data").Parent.Name

我最初说应该是:

CaseCount = Application.WorksheetFunction.CountIf(Worksheets("Case Data").Columns("A"), CaseID)

但这是错误的,因为我再次使用了对当前工作簿的隐式引用

如果您是我,请通过removing the Select statements并使用 Explicit 引用而不是隐式引用(即Sheet.Columns vs Columns)来清理代码。

Dim Book as Workbook
Dim Sheet as Worksheet
Set Book = ThisWorkbook ' Or ActiveWorkbook or Workbooks("File ABC.xlsx")
Set Sheet = Book.Worksheets("Case Data")
With Sheet
    CaseID = .Cells(2, "D").Value
    '''
    CaseCount = Application.WorksheetFunction.CountIf(.Columns("A"), CaseID)
End With