2017-10-16 273 views
0

我试图在Excel宏中使用Application.CountIf()并且它没有返回一个计数。它返回的数字为0.Excel VBA Application.CountIf()不能像其他宏一样工作

我觉得这很让人困惑,因为我在另一个宏中多次使用了Application.CountIf()。从其他宏观

工作代码:

Sub newer_COA() 
    Sheets("BATCH NUMBERS").Select 

    'Count total of column CO 
    count = Application.CountIf(Columns(93), "1") 
End Sub 

新宏的代码 - sum_litres()

0 Number of entries from Machine one 
- sum_litres()

Sub sum_litres() 
    Workbooks("Small Fill.xlsm").Activate 
    Sheets("Small Fill").Select 

    'Count total Machine one entries in column F 
    Dim Machine_one_count As Integer 
    Machine_one_count = Application.CountIf(Columns(6), "1") 

    Workbooks("Small Fill Analysis.xlsm").Activate 
    Sheets("Sheet1").Select 

    Msg = Machine_one_count & " Number of entries from Machine one" 
    MsgBox Prompt:=Msg 
End Sub 

由新宏输出

我在一个名为Small Fill Analysis的单独工作表中创建这个新的宏sum_litres(),该工作表获取工作表Small Fill.xlsm来查看数据。在sum_litres()开始时,它使用下面的功能来检查工作表Small Fill.xlsm是否已打开,并在工作表尚未打开时成功打开它。由于此代码正常工作,我没有在上面的问题中包含它。

'Calls function IsWorkBookOpen() to check if the required spreadsheet is open 
Ret = IsWorkBookOpen("Small Fill.xlsm") 

If Ret = True Then 
    Workbooks("Small Fill.xlsm").Activate 
    Sheets("Small Fill").Select 
Else 
    'Open required spreadsheet 
    Workbooks.Open FileName:="Small Fill.xlsm", ReadOnly:=True 
    Sheets("Small Fill").Select 
End If 


Function IsWorkBookOpen(ByVal FileName As String) As Boolean 
    Dim TargetWorkbook As Workbook 

    Dim IteratorWorkbook As Workbook 
    For Each IteratorWorkbook In Application.Workbooks 
     If IteratorWorkbook.FullName = FileName Then 
      Set TargetWorkbook = IteratorWorkbook 
     End If 
    Next 

    If Not TargetWorkbook Is Nothing Then 
     If TargetWorkbook.ReadOnly Then 
      IsWorkBookOpen = True 
      Exit Function 
     End If 
    End If 
End Function 

非常感谢您的任何建议!

+0

你肯定在表的6列中的任何行“小填写“有一个值”1“?另外,该示例的列是以文本格式还是数字格式? – Moacir

+0

不确定这是否与您的CountIf问题相关,但您的IsWorkbookOpen函数需要完整的路径地址,因为它将FileName与IteratorWorkbook.FullName(它提供了完整路径)进行比较。如果您将其称为IsWorkbookOpen(“Small Fill.xlsm”),它将始终返回false。 –

+0

谢谢@Moacir表格“小填充”第6栏(F)确实有一对数值为“1”的数字。工作示例的列被格式化为“常规”,并从下拉列表中选择值。我不知道“Small Fill”中数据的格式,因为这不是我的表格,所以我刚刚检查了“Small Fill”表的列,第6列也格式化为“常规”,但值是没有从下拉列表中选择。这些信息是否更有意义? –

回答

0

我怀疑的问题是宏观的位置,但解决的办法很简单,就是不选择的东西,但直接引用范围:

Sub sum_litres() 
    'Count total Machine one entries in column F 
    Dim Machine_one_count As Integer 
    Machine_one_count = Application.CountIf(Workbooks("Small Fill.xlsm").Sheets("Small Fill").Columns(6), "1") 

    Msg = Machine_one_count & " Number of entries from Machine one" 
    MsgBox Prompt:=Msg 
End Sub