循环遍历特定的列和行

时间:2017-04-28 09:17:52

标签: excel vba excel-vba

我是VBA的新手,我正在尝试使用特定的周边循环遍历列和行。我已完成行,但移动列证明是困难的。

由于此时未上传代码,我拍了一张照片。我希望从5开始向下移动一列,然后每3个位置向下移动直到大约41,然后从5开始向右移动每两个向右移动直到第14行(关于字母P)。

任何帮助将不胜感激。

它目前打印出我想要的两行,但我不知道如何继续移动到下一行。

Private Sub CommandButton21_Click()

Dim X As Integer
Dim Y As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim Q As Integer
Dim r As Integer

X = 5
j = 5
k = 2
Q = 5
r = 4

For i = 1 To j
   Cells(X, k).Value = 5
   X = X + 3

   For Y = 1 To 1
      Cells(Q, r).Value = 2
      Q = Q + 3

   Next Y
Next i

End Sub

3 个答案:

答案 0 :(得分:0)

这应该是如何循环特定工作簿中的单元格的一个很好的示例。您可以将Sheet1更改为所需工作表的名称。

Option Explicit 'use this at the top of your module 
                'see: http://stackoverflow.com/documentation/excel-vba/1107/vba-best-practices/3554/always-use-option-explicit

Public Sub LoopThroughRowsAndCols()
    Dim iRows As Long, iCols As Long

    For iRows = 5 To 41 Step 3 'loop through rows: start at row 5 end at row 41 every third row (steps)
        For iCols = 5 To 14 Step 2 'loop through columns: start at columns 5 end at columns 14 every second column (steps)
            ThisWorkbook.Worksheets("Sheet1").Cells(iRows, iCols).Value = "AAA" 'write somthing into the cells we looped through
        Next
    Next
End Sub

答案 1 :(得分:0)

不要使用Cells()因为引用是绝对的(从A1开始计算)。使用相对定位,如下例所示。

成像您有一个从C9开始的值表,如下所示:

pic

下面有几个例子,说明如何使用范围.Offset().Resize()函数读取或写入此表的值。

Option Explicit

Public Sub SOWUT()

    Dim r As Range
    Set r = Range("C9")

    Dim nrows As Long, ncols As Long
    ' Count the filled rows
    nrows = Range(r, r.End(xlDown)).Rows.count
    ' Specify the column count
    ncols = 4

    Dim i As Long, j As Long
    ' Go down every third row and add the values
    ' Repeat for each second column
    Dim sum As Double
    For j = 1 To ncols Step 2
        sum = 0#
        For i = 1 To nrows Step 3
            sum = sum + r.Offset(i - 1, j - 1).Value
        Next i
        ' Add the sum below that table values
        r.Offset(nrows, j - 1).Value = sum
    Next j

    ' Avergage all the  values in the 2nd column
    Dim ave As Double
    ave = WorksheetFunction.Average(r.Offset(0, 1).Resize(nrows, 1))
    ' Write the results into cell C5
    [C5] = ave

    ' Read in the table in a memory array
    Dim vals() As Variant
    vals = r.Resize(nrows, ncols).Value
    'Loop through all rows and columns and count values >= 5
    Dim count As Long
    count = 0
    For j = 1 To ncols
        For i = 1 To nrows
            If vals(i, j) >= 5 Then
                count = count + 1
            End If
        Next i
    Next j

End Sub

答案 2 :(得分:-1)

代码的逻辑可能有点奇怪,但它有效。如果这是你想要的,请告诉我。

Sub test()
    Dim X, Y As Integer

    For j = 1 To 16
        For k = 2 To 10

            a = (Right(j / 2, 1))
            If a <> 5 Then
                Cells((k * 3) - 1, j * 2).Value = 2
            Else
                Cells((k * 3) - 1, j * 2).Value = 5
            End If
        Next
    Next 
End Sub