[英]VBA FOR loop to increment columns
'Calculating Sum of Max. values of Eth column from pivot table values
Dim lastRowE As Long
lastRowE = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
'Excluding grandtotal
lastRowE = lastRowE - 1
Worksheets("pmrrcconnmax").Activate
Cells(1, 5).Value = WorksheetFunction.SumIfs(Range("E7:E" & lastRowE), _
Range("E7:E" & lastRowE), ">0")
'Calculating Sum of Max. values of Fth column from pivot table values
'Dim lastRowF As Long
lastRowF = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
'Excluding grandtotal
lastRowF = lastRowF - 1
'Worksheets("pmrrcconnmax").Activate
Cells(1, 6).Value = WorksheetFunction.SumIfs(Range("F7:F" & lastRowF), _
Range("F7:F" & lastRowF), ">0")
'Calculating Sum of Max. values of Gth column from pivot table values
'Dim lastRowG As Long
lastRowG = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
'Excluding grandtotal
lastRowG = lastRowG - 1
'Worksheets("pmrrcconnmax").Activate
Cells(1, 7).Value = WorksheetFunction.SumIfs(Range("G7:G" & lastRowG), _
Range("G7:G" & lastRowG), ">0")
等等......直到Kth專欄(因為我是VBA新手)。 有人可以幫助我找到將它們放入for循環或任何其他合適循環的方法嗎?
先感謝您
如果我理解正確的,並且要使用for
VBA中,每次引用不同的細胞,嘗試這個例子:
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
嘗試這個。 它只會從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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.