Excel VBA:在CountIf函数中使用variables

我无法克服这个在countif函数中使用variables的看似简单的问题 – 希望你们可以帮忙。 我循环遍历2006年到2024年的数据列表,使用if语句来确定我的search范围的开始和结束,这将在代码结尾的countif函数中使用。 do / loop部分适当地定义范围,但是当macros尝试使用包含search范围的variables将countif函数放置在指定的单元格中时,我会收到错误。 这是我的代码:

Dim Year As Integer Dim Month As Integer Year = InputBox("Enter the Current Year", "Choose Year for Analysis", "Type your desired year here") If Len(Year) = 0 Then MsgBox "No year chosen, this macro will now end)" Exit Sub End If Month = InputBox("Enter the first # that corresponds with the first month you would like to review", "Starting Month", "Enter the # that corresponds with your desired month here") If Len(Year) = 0 Then MsgBox "No month chosen, this macro will now end)" Exit Sub End If Dim SearchStart As Range Dim SearchEnd As Range Dim searchrange As Range 'standard Range("L2").Select Do Until ActiveCell.Value = Year And ActiveCell.Offset(0, 1).Value > Month + 1 If ActiveCell.Value = Year And ActiveCell.Offset(-1, 0).Value = Year And ActiveCell.Offset(0, 1).Value = Month And ActiveCell.Offset(-1, 1).Value = Month Then ActiveCell.Offset(1, 0).Select Else If ActiveCell.Value = Year And ActiveCell.Offset(-1, 0).Value = Year And ActiveCell.Offset(0, 1).Value = Month + 1 And ActiveCell.Offset(-1, 1).Value = Month + 1 Then ActiveCell.Offset(1, 0).Select Else If ActiveCell.Value = Year And ActiveCell.Offset(-1, 0).Value = Year And ActiveCell.Offset(0, 1).Value = Month + 1 And ActiveCell.Offset(-1, 1).Value = Month Then ActiveCell.Offset(1, 0).Select Else If Not ActiveCell.Value = Year And ActiveCell.Offset(0, 1).Value = Month And SearchStart Is Nothing Then ActiveCell.Offset(1, 0).Select Else If ActiveCell.Value = Year And ActiveCell.Offset(0, 1).Value = Month And Not IsEmpty(SearchStart) Then ActiveCell.Offset(0, -1).Select Set SearchStart = Selection ActiveCell.Offset(1, 1).Select End If End If End If End If End If If ActiveCell.Value < Year Then ActiveCell.Offset(1, 0).Select Else If ActiveCell.Value < Year And ActiveCell.Offset(0, 1).Value < Month Then ActiveCell.Offset(1, 0).Select If ActiveCell.Value = Year And ActiveCell.Offset(0, 1).Value < Month Then ActiveCell.Offset(1, 0).Select End If Loop ActiveCell.Offset(-1, -1).Select Set SearchEnd = ActiveCell Range(SearchStart.Address, SearchEnd.Address).Select Set searchrange = Selection 'formula to find: Current month QTY & next month QTY Range("z2").Select Selection.FormulaR1C1 = "=COUNTIF(" & searchrange.Address & ",RC[-1])" 

在这块代码中,你正在混合如何处理范围:

 Selection.FormulaR1C1 = "=COUNTIF(" & searchrange.Address & ",RC[-1])" 

您需要使用R1C1语法:

 Selection.FormulaR1C1 = "=COUNTIF(" & searchrange.Address(ReferenceStyle:=xlR1C1) & ",RC[-1])" 

仅供参考,你应该避免使用Select ,所以你可以取代:

 Range("z2").Select Selection.FormulaR1C1 = "=COUNTIF(" & searchrange.(AddressReferenceStyle:=xlR1C1) & ",RC[-1])" 

附:

 Range("z2").FormulaR1C1 = "=COUNTIF(" & searchrange.Address(ReferenceStyle:=xlR1C1) & ",RC[-1])"