【问题标题】:If function to check multiple column conditions across multiple sheets如果功能检查跨多个工作表的多个列条件
【发布时间】:2022-06-10 19:22:06
【问题描述】:

我正在启动一个收集每周数据的 Excel 工作表,并且我正在尝试创建一个 if 语句来访问工作簿中的最后一个(索引)工作表并检查多个条件。

我需要检查 k 列中的单元格是否为“真”,如果是,则 J 列中的日期是否在名为“仪表板”的工作表的月份范围内。如果满足这两个条件,我将在我的计数器中添加一个,然后最终将此计数器编号打印到仪表板工作表上的单元格中。

到目前为止,我的代码是:

Sub CreateTable()
Dim n As Integer, RangeCount As Integer
Dim MaxVal As Long

n = 0
RangeCount = 1
sheets(sheets.Count).Select) 'I don't want this line but I don't know how else to access the final sheet in code
MaxVal = WorksheetFunction.CountA(Range("J1:J14")) 'Columns J and K will always be the same length
For RangeCount = 1 to MaxVal
    If Cells(RangeCount, 11) = "true" And Sheets("Dashboard").Range("Y17") <= sheets(sheets.Count).Select.Cells(RangeCount, 11) And sheets("Dashboard").WorksheetFunction.EoMonth(Range("Y17", 0)) >= Cells(RangeCount, 11) Then
       n = n + 1
    End If
Next RangeCount
End Sub

Y17 是仪表板中列出月份的单元格 (1/12/2022)。 我当前的错误是需要对象,但我想我已经定义了我需要定义的所有内容等。任何帮助将不胜感激!

【问题讨论】:

  • 欢迎来到 SO。试试sheets(sheets.Count).Cells(RangeCount, 11) 而不是sheets(sheets.Count).Select.Cells(RangeCount, 11)

标签: excel vba loops for-loop if-statement


【解决方案1】:

您的条件有问题吗?

Option Explicit

Sub CreateTable()
Dim n As Integer, RangeCount As Integer
Dim MaxVal As Long

n = 0
RangeCount = 1
Sheets(Sheets.Count).Select                         'I don't want this line but I don't know how else to access the final sheet in code
MaxVal = WorksheetFunction.CountA(Range("J1:J14"))  'Columns J and K will always be the same length
For RangeCount = 1 To MaxVal
    If CheckConditions(RangeCount) Then
       n = n + 1
    End If
Next RangeCount
End Sub


Function CheckConditions(locCnt As Integer) As Boolean    
Dim locTest As Boolean

'which worksheet? do you want the activesheet here?
locTest = Cells(locCnt, 11) = "true"  

locTest = locTest And Sheets("Dashboard").Range("Y17") <= Sheets(Sheets.Count).Cells(locCnt, 11)

'which worksheet for cells? do you want the activesheet here?
locTest = locTest And Sheets("Dashboard").WorksheetFunction.EoMonth(Range("Y17", 0)) >= Cells(locCnt, 11)

CheckConditions = locTest
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2017-08-11
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多