循环IF语句通过每一列

时间:2017-01-13 17:37:26

标签: excel vba excel-vba

我下载了调查结果并将其放入Excel中。

我可以将此宏应用于“A”列。

var result = controller.addData(...);
expect(result).toBe(expected);

“B-R”都具有与“A”列相同的条件。而不是键入此代码

Private Sub CommandButton1_Click()

counter = 2 'moves output

For Each n In [A7:A50]  'loops through cell in specified range

    If n < 400 Then
        Sheets("Output").Cells(counter, "B") = 0 'Output to other sheet, = points awarded
    ElseIf n > 400 Then
        Sheets("Output").Cells(counter, "B") = 3 'Output to other seet, = points awarded
    End If

    counter = counter + 1 'moves counter up 1

Next

End Sub

只需切换“A”和输出列,就可以循环我的计数器和我的if语句。

我的脚本查看“结果工作表”中的列/行A7:A50,在“输出工作表”的B列中生成点。

我无法查看B列(结果工作表)然后输出到(输出工作表)中的C列,然后查看C列(结果工作表),然后输出到D列(输出工作表)

2 个答案:

答案 0 :(得分:1)

编辑答案,希望能解决您的问题。我看到了一些事情。

首先,我认为您需要在结果进入之前激活每个工作表。其次,在确定要输出的单元格之后使用.value。第三,Cells()函数使用整数,因此“B”应为2。

尝试使用以下代码,看看它是否适合您。


Private Sub CommandButton1_Click()
    Dim r as Long
    Dim c as Long
    Dim lastrow as Integer
    Dim lastcol as Integer
    Dim cpath as String

    cpath = Worksheets("SHEETNAME") 'less typing later on
    cpath2 = Worksheets("Output")
    lastrow = WorksheetFunction.CountA(Range("A:A"))
    lstcolm = WorksheetFunction.CountA(cpath.Rows(1).EntireRow)
    cpath.Cells(2,1).Activate   'assuming you have a header row


    For c = 1 to lastcol
    For r = 2 to lastrow

If cpath.cells(r,c).value < 400 Then

cpath2.Activate
    cpath2.Cells(r, 2).value = 0
ElseIf n > 400 Then

cpath2.Activate
    cpath2.Cells(r, 2).value = 3
End If

cpath.activate

next r
next c 

End Sub

答案 1 :(得分:1)

也许这会对你有所帮助:

Private Sub CommandButton1_Click()

Dim rng As Range
Dim i As Integer

Set rng = Range("A:R") ' define your range

For i = 1 To rng.Columns.Count ' loop through the columns

    counter = 2 'moves output

    For Each n In Range(Cells(7, i), Cells(50, i)) 'loops through cell in specified column i 

    If n < 400 Then
        Sheets("Output").Cells(counter, i + 1) = 0 'Output to other sheet, = points awarded
    ElseIf n > 400 Then
        Sheets("Output").Cells(counter, i + 1) = 3 'Output to other seet, = points awarded


    End If

    counter = counter + 1 'moves counter up 1

    Next
Next i

End Sub

我添加了一个循环,遍历范围A:R中的每一列,并为每个列应用宏。我在if语句中替换了“B”,因此结果将应用于所需的列:

评估列“A” - &gt;更新栏目“B”,

评估列“B” - &gt;更新列“C”......

这有帮助吗?

相关问题