循环内的VBA偏移

时间:2018-04-25 11:06:24

标签: excel vba excel-vba loops offset

我在循环中组合VBA偏移函数时遇到问题。本质上,我试图根据搜索词(survey值)从一列数据中提取多组值。我可以让这个用于一个术语,但我希望创建一个宏,它将一次提取所有术语的所有值。

数据的设置是原始数据(indicators)的列(c6:c50),然后是13列(j6:j50,m6:m50等)(output)其中应该出现提取的值。列K和L(在最初的13列之间等等)包含基于列J的值的公式.13列中每列的搜索项位于范围正上方的单元格中(J5,M5等)。 / p>

以下代码是我所需要的。目的是建立一个循环,将C列中的值提取到J列(基于'i'的循环),然后是第二个循环(基于'j'的循环),这些循环在列之间进行偏移。

运行此操作时会发生单元格J6中的第一个单元格值填充,然后是J7中的正确值。然后,所有后续提取的值都会覆盖J7中的值。一旦第一个项的循环完成,它将偏移3列,从J6中提取相同的值到M6(可能是因为搜索词'survey'没有偏移?)但是然后返回覆盖单元格J7。

非常感谢任何帮助。

Sub indicator_charts()

Dim indicators As Range
Dim survey As String
Dim surveyrng As Range
Dim output As Range
Dim survey2 As String
Dim firstcell As Range

Set indicators = Worksheets("Indicator Summary").Range("C6:C50")
Set output = Worksheets("Indicator Summary").Range("j5:j50")
Set surveyrng = Worksheets("Indicator Summary").Range("J5")
Set firstcell = Worksheets("Indicator Summary").Range("J6")

survey = surveyrng.Value

For j = 0 To 36 Step 3
output.Offset(0, j) = output
surveyrng.Offset(0, j) = surveyrng
firstcell.Offset(0, j) = firstcell
    For i = 1 To 46
        If InStr(1, indicators.Cells(i, 1).Value, survey) Then
        survey2 = indicators.Cells(i, 1).Value
            If IsEmpty(firstcell) Then
            firstcell.Value = survey2
            Else
            output.End(xlDown).Offset(1, 0).Value = survey2
            End If
        End If
    Next i
Next j

End Sub

1 个答案:

答案 0 :(得分:0)

我修改了你的代码。应该做你想要的。

Sub indicator_charts()

Dim indicators As Range
Dim survey As String
Dim surveyrng As Range
Dim output As Range
Dim survey2 As String
Dim firstcell As Range
Dim OutputVar As Variant
Dim SurveyRngVar As Variant
Dim FirstCellVar As Variant

Set indicators = Worksheets("Indicator Summary").Range("C6:C50")
Set output = Worksheets("Indicator Summary").Range("j5:j50")
Set surveyrng = Worksheets("Indicator Summary").Range("J5")
Set firstcell = Worksheets("Indicator Summary").Range("J6")

For j = 0 To 36 Step 3
Set OutputVar = output.Offset(0, j)
Set SurveyRngVar = surveyrng.Offset(0, j)
Set FirstCellVar = firstcell.Offset(0, j)
survey = SurveyRngVar.Value

    For i = 1 To 46
        If InStr(1, indicators(i, 1).Value, survey) Then
        survey2 = indicators(i, 1).Value
            If IsEmpty(FirstCellVar) Then
            FirstCellVar.Value = survey2
            Else
            OutputVar.End(xlDown).Offset(1, 0).Value = survey2
            End If
        End If
    Next i

Next j

End Sub