VBA FOR循环增加列

时间:2016-10-29 19:23:19

标签: vba excel-vba excel

$('li').has('ul').addClass('has-children');
// OR
$('li:has(ul)').addClass('has-children');

依旧......直到Kth专栏(因为我是VBA的新手)。有人可以帮我找到将它们放入for循环或任何其他合适循环的方法吗?

提前谢谢

2 个答案:

答案 0 :(得分:1)

如果我理解正确,并且您想在VBA中使用for并且每次都引用不同的单元格,请尝试以下示例:

Dim row As Integer
Dim col As Integer

For row = 1 To 10
    For col = 1 To 10
        Cells(row, col).Value = 1
    Next
Next

它以10x10填充单元格,值为1。

使用Cells,您可以轻松插入整数变量来选择单元格。

你也可以将它与Range结合使用,例如:

Range(Cells(1, 1), Cells(5, 5)).Select

你也可以选择这样的整列:

Columns(5).Select

答案 1 :(得分:0)

试试这个。它只会从E循环到K.

Option Explicit

Sub Add_Formulas()

'Declaring the variable lColumn as long to store the last Column number
Dim lColumn As Long
'Declaring the variable iCntr as long to use in the For loop
Dim iCntr As Long, iCell As Long
Dim ColLetter As String
Dim lastCol As Long, lastRow As Long
Dim wks As Worksheet

' Set wks so it is the activesheet
Set wks = ThisWorkbook.ActiveSheet

'lastCol = wks.Cells(1, wks.Columns.Count).End(xlToLeft).Column
' Using column D as you are using column no. 4 in your code
lastRow = wks.Range("D" & wks.Rows.Count).End(xlUp).Row

'Excluding grandtotal
lastRow = lastRow - 1

'Assigning the last Column value to the variable lColumn
'lColumn = lastCol
lColumn = 11

'Using for loop
' 5-11 = E-K
For iCntr = lColumn To 5 Step -1

    ColLetter = GetColumnLetter(iCntr)
    Cells(1, iCntr).Value = WorksheetFunction.SumIfs(Range(ColLetter & "7:" & ColLetter & lastRow), _
                                         Range(ColLetter & "7:" & ColLetter & lastRow), ">0")
Next

End Sub

Function GetColumnLetter(colNum As Long) As String
Dim vArr
vArr = Split(Cells(1, colNum).Address(True, False), "$")
GetColumnLetter = vArr(0)
End Function