Excel宏以比较值

时间:2018-10-08 10:33:23

标签: excel excel-vba if-statement compare cell

我需要你的帮助 我想知道是否有任何vba脚本可以使我的工作更轻松 截至目前,我正在使用IF和AND条件 我想用一个宏来改变它 因此,我可以选择范围并隐蔽到“ 1”和“ 0”

我要做的就是将每一列中的值与每一列中的1个单元格中的正确答案进行比较 将1标记为0,将0标记为不匹配

谢谢 任何帮助将非常有用

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找类似以下VBA代码的内容。该代码是动态的,因此您的表大小可以变化。您可以在以下位置设置数据表(候选R1)的开始列:

Const ColStart As Integer = 2

以及最后一栏(候选R10)

Const ColEnd As Integer = 11

VBA代码

Sub FormulaToCompare()

Dim lrow As Integer
Dim lrowCandidate As Integer
Dim NextFree As Integer

Const ColStart As Integer = 2 'Which column your data table start at (R1). R1 is in Column B = Column 2
Const ColEnd As Integer = 11 'Which column your data table start at (R1). R1 is in Column B = Column 2


lrowCandidate = Cells(Rows.Count, 1).End(xlUp).Row 'Find the last row of the Column Candidate (Column A)

Range(Cells(1, 1), Cells(2, ColEnd)).Offset(lrowCandidate + 2, 0).Value = Range(Cells(1, 1), Cells(2, ColEnd)).Value 'Copy Headers to 2nd table
Range(Cells(3, 1), Cells(lrowCandidate, 1)).Offset(lrowCandidate + 2, 0).Value = Range(Cells(3, 1), Cells(lrowCandidate, 1)).Value 'Copy Candidate numbers to 2nd table

For i = ColStart To ColEnd 'Loop from start column to end column of data, Column i
    NextFree = Range(Cells(1, i), Cells(Rows.Count, i)).Cells.SpecialCells(xlCellTypeBlanks).Row - 1 'Find the last row starting from above in Column i EXCLUDING 2nd table.
    lrow = Cells(Rows.Count, i).End(xlUp).Row 'Find the last row starting from above in Column i INCLUDING 2nd table.
        For j = 3 To NextFree 'Loop from row 3 (2 rows are headers, therefore we start at row 3) to last row excluding 2nd table
            Cells(lrow + j - 2, i).FormulaR1C1 = "=IF(AND(R[-" & NextFree + 2 & "]C<>0, R[-" & NextFree + 2 & "]C=R1C),1,0)" 'Find the cell to paste the formula into. The formula is dynamic
        Next j
Next i
End Sub