在Excel VBA中选择各种值

时间:2013-07-01 07:26:12

标签: excel excel-vba excel-2013 vba

所以这里是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,最好的方法是如何实现这一目标?

1 个答案:

答案 0 :(得分: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

以及其他一些混合选项。