0

所以这是我在 Excel VBA 中的代码

Sub GetValue()

Dim rRH, rYear, r1 As Range
Dim RowIndex, ColIndex, yearRow As Integer
Dim rh1 As Integer
Dim rh1Pct As Double
Dim year As String

RowIndex = 30
yearRow = 10

Do While RowIndex < (RowIndex + yearRow)
    Set rRH = ThisWorkbook.Sheets("CF-Apar").Range("M" & CStr(RowIndex))

    If rRH.Value <> "" Then
        rh1 = rRH.Value
        year = ThisWorkbook.Sheets("CF-Apar").Range("A" & CStr(RowIndex)).Value
        Exit Do
    End If

    RowIndex = RowIndex + 1
Loop

RowIndex = 12
rh1Pct = Range("D12").Value

ColIndex = 0
Set rYear = Range("D120")
Do While ColIndex < yearRow

    If CInt(year) > CInt(rYear.Value) Then
        Set r1 = rYear
        r1.Offset(123, 0).Value = "0"
    End If

    If year = rYear.Value Then
        rYear.Offset(123, 0).Value = rh1 * rh1Pct
        Exit Do
    End If

    Set rYear = rYear.Next
    Set r1 = r1.Next
Loop
End Sub

该代码是每当更改 CF-Apar 工作表中的值时更改或移动当前单元格中的值,但当前代码仅覆盖一个范围(对于这种情况,它是 M,在 CF-Apar 索引中),问题是,如何添加更多范围单元格,例如从 M30 到 Q40,最好的方法是如何做到这一点?

4

1 回答 1

1

正如评论中所建议的,您需要使用嵌套循环。这应该如下所示(下面的建议代码未经测试):

'beginning of your sub here

'additional loop
Dim i as Byte
For i=13 to 17 'columns M to Q

'your loop but changed inside
Do While RowIndex < (RowIndex + yearRow)
    Set rRH = ThisWorkbook.Sheets("CF-Apar").Cells(RowIndex, i)

    If rRH.Value <> "" Then
        rh1 = rRH.Value
        year = ThisWorkbook.Sheets("CF-Apar").Cells(RowIndex, i).Value
        Exit Do
    End If

    RowIndex = RowIndex + 1
Loop

RowIndex = 30
Next i
'rest of your code here

编辑以解释评论中的问题。您的一些替代选择:

A)我的代码中的基本解决方案

Set rRH = ThisWorkbook.Sheets("CF-Apar").Cells(RowIndex,i)
'....
rh1 = rRH.Value   'for column i

B)您的代码的替代解决方案

Set rRH = ThisWorkbook.Sheets("CF-Apar").Cells(RowIndex, i)
Set rRH1 = ThisWorkbook.Sheets("CF-Apar").Cells(RowIndex, "N")
'....
rh1 = rRH.Value   'for column i
rh2 = rRH2.Value  'for column N

C)您的代码的替代解决方案

Set rRH = ThisWorkbook.Sheets("CF-Apar").Cells(RowIndex, "M")
'....
rh1 = rRH.Value   'for column M
rh2 = rRH2.Offset(0, 1).Value  'for column N

以及其他一些混合选项可用。

于 2013-07-01T10:25:46.167 回答