如何使用Excel VBA宏循环行?
我是VBA新手,但对PHP很不错。话虽这么说,我用VBA循环挣扎......如何使用Excel VBA宏循环行?
我有这样的片材40行称为“SH1”:
SH1
A B C D E
1 2 One 1.0a 12
2 7 Two 2.0b 34
3 13 Three 3.0c 56
4 14 Four 4.0d 78
..
40
我需要遍历40行,并检查在列中的值答:如果列A中的值符合我的标准(请参见下文),则生成一些输出并将其放入另一张表中。
我的输出表是3列,被称为 “SH2”:
SH2
A B C D E
1 1.0a 12 One
2.0b 34 Two
2 3.0c 56 Three
4.0d 78 Four
..
15
我来决定所发生的标准,其中:
// First loop:
if a1 < 8, put c1 in SH2 a1, put d1 in SH2 b1, put b1 in SH2 c1
if a2 < 8, put c2 in SH2 a1, put d2 in SH2 b1, put b2 in SH2 c1
// ... loop through a40 ...
然后:
// Second loop:
if a1 > 8 AND a1 < 16, put c1 in SH2 a2, put d1 in SH2 b2, put b1 in SH2 c2
if a2 > 8 AND a2 < 16, put c2 in SH2 a2, put d2 in SH2 b2, put b2 in SH2 c2
// ... loop through a40 ...
进展编辑:
似乎工作,但想知道是否有一个“更干净”的方式?
Sub CatchersPick2()
Dim curCell As Range
For Each curCell In Sheet4.Range("C3:C40").Cells
If curCell.Value > 0 And curCell.Value < 73 Then
cLeft = cLeft _
& curCell.Offset(0, 5) & "." _
& curCell.Offset(0, 6) & vbLf
cMidl = cMidl _
& curCell.Offset(0, -2) & ", " _
& curCell.Offset(0, -1) & " " _
& curCell.Offset(0, 7) & vbLf
cRght = cRght _
& curCell.Offset(0, 9) & " " _
& curCell.Offset(0, 2) & " " _
& curCell.Offset(0, 11) & " " _
& curCell.Offset(0, 10) & vbLf
End If
Next curCell
Sheet6.Range("B3") = cLeft
Sheet6.Range("C3") = cMidl
Sheet6.Range("D3") = cRght
Sheet6.Range("B3:D3").Rows.AutoFit
Sheet6.Range("B3:D3").Columns.AutoFit
End Sub
Dim cell As Range
For Each cell In Range("a1:a40")
'do stuff here
Next cell
您可以cell.Row
得到您的当前行。祝你好运^ _^
这里没有
首先,不使用单词“细胞”作为一个变量,它可以工作了很多你可以做,但是......,但它在玩火,所以
Dim curCell as Range
其次,你应该通过范围的单元格属性循环
For Each curCell In Range("C3:C40").Cells
第三,你不需要选择单元格,你可以操纵curCell变量
最后,你不需要使用ActiveCell,只需使用curCell变量。
If curCell.Value < 35 And curCell.Value > 0 Then
cLefta = curCell.Offset(0, 5) & "."
其实,你也可以只使用像“C”短变,把整个事情上一行:
cLeft = c.Offset(0,5) & "." & c.Offset(0,6) & vblf
注意:如果您的设置为接近于每次都在同,使用工作表函数可能会更容易。
优秀信息,谢谢!我使用这一行进行连接:`cLeft = cLeft&curCell。偏移(0,5)&“。” &curCell.Offset(0,6)&vbLf`。更新了我的功能以反映更改。 – Jeff 2011-02-10 17:21:46
如何:
Sub Catchers()
Dim cell As Range
Sheet1.Select 'SHEET: C
For Each cell In Range("C3:C40")
If cell.Value < 35 And cell.Value > 0 Then
With Sheet6
.Range("B" & cell.Row) = cell.Offset(0, 5) _
& "." & cell.Offset(0, 6)
.Range("C" & cell.Row) = cell.Offset(0, -2) _
& ", " & cell.Offset(0, -1) _
& " " & cell.Offset(0, 7)
.Range("D" & cell.Row) = cell.Offset(0, 9) _
& " " & cell.Offset(0, 2) _
& " " & cell.Offset(0, 11) _
& " " & cell.Offset(0, 10)
End With
End If
Next cell
Sheet6.Range("B4:D4").Rows.AutoFit
Sheet6.Range("B4:D4").Columns.AutoFit
End Sub
抱歉,但是这看起来相当混乱,似乎不匹配前面的东西。顺便说一句,你说`如果a2> 8 AND a1 8 AND a2 Fionnuala 2011-02-10 16:04:17
我以前的东西只是一个构建在我需要生成的裸露输出上的示例。我上面的例子工作,但是VBA循环和变量是新手,我确信有一个更清晰的方法(帮助!)。回答你的问题,“是的”,这是一个错字。 – Jeff 2011-02-10 16:06:58