使用带偏移量VBA的绝对参考

时间:2016-07-21 13:05:16

标签: excel vba reference offset absolute

我目前正在努力开发:

首先,使用循环填充数字0到1500,每个分开8列,然后使用另一个循环来填充另一个工作表中的值,但我想使用偏移量,因此数字0到1500是行数我想每次都要抵消。所以0行,1行,2行等。

我试图绝对引用我将偏移另一张表上的值的列(称为DEX Spread Report(Corp))。但是,我无法完全引用该列(D列第7行),因为我不熟悉VBA的方法。

非常感谢帮助!感谢

Sub Output_Numbers_For_Purpose_of_Offsetting_From_DexCorp()

Dim i As Integer
Dim m As Integer

Sheets("Sheet1").Select
Range("B1").Select

For i = 0 To 1500

    ActiveCell.Value = i
    ActiveCell.Offset(0, 8).Select

Next i

Range("B1").Select

For m = 0 To 1500

If ActiveCell.Value = m Then
ActiveCell.Offset(1, 0).Value = "=Offset('DEX Spread Report (Corp)'!   (Range("D7").FormulaR1C1 = "C[0]*10"), m, 0)
Else: ActiveCell.Offset(1, 0).Value = ""
End If

ActiveCell.Offset(8, 0).Select
Next m
End Sub

编辑 - 将评论合并代码

我遇到了一个问题:

ActiveCell.Offset(1, 0).Value = "=Offset('DEX Spread Report (Corp)'! (Range("D7").FormulaR1C1 = "C[0]*10"), m, 0)

我正在尝试将其构建为:

ActiveCell.Offset(1, 0).Value = Offset('DEX Spread Report (Corp)'!$D7,m,0 ) 

3 个答案:

答案 0 :(得分:0)

一种方式:

 Dim r As Range

For Each r In Range("B1:B1000")

    If r.Value = m Then
    'stuff
    Else
    'stuff
    End If

Next r

另一种方式:

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

For m = 1 To 1500

    If r(m, 1).Value = m Then
    'stuff
    Else
    'something else
    End If


Next m

答案 1 :(得分:0)

如果我正确地关注了您,您似乎正试图让您的公式偏移$D7参考,就像您已将其手动粘贴到B2并将其复制到工作表中一样。

我会提供另一种解决方案,因为你似乎知道你总是想要偏移8行。而不是处理VBA想要绝对单元格引用,为什么不只计算行数? (m * 8) + 7会在$D70$D15提供1,依此类推。

Sub Output_Numbers_For_Purpose_of_Offsetting_From_DexCorp()

    Dim i As Integer
    Dim m As Integer

    Sheets("Sheet1").Select
    Range("B1").Select

    For i = 0 To 1500
        ActiveCell.Value = i
        ActiveCell.Offset(0, 8).Select
    Next i

    Range("B1").Select
    For m = 0 To 1500
        If ActiveCell.Value = m Then
            ActiveCell.Offset(1, 0).Value = "=Offset('DEX Spread Report (Corp)'!$D" & (m * 8) + 7 & "," & m & ", 0)"
            Else: ActiveCell.Offset(1, 0).Value = ""
        End If

        ActiveCell.Offset(0, 8).Select
    Next m
End Sub

答案 2 :(得分:0)

很难遵循您的代码

也许你是这样的:

Option Explicit

Sub Output_Numbers_For_Purpose_of_Offsetting_From_DexCorp()
    Dim i As Long

    With Sheets("Sheet1")
        For i = 0 To 1500
            .Range("B1").Offset(, i * 8) = i
        Next i

        For i = 0 To 1500
            With .Range("B1").Offset(i * 8)
                If .Value = i Then
                    .Offset(1, 0).Value = Worksheets("DEX Spread Report (Corp)").Range("D7").Offset(i + 6)
                Else
                    .Offset(1, 0).Value = ""
                End If
            End With
        Next i
    End With
End Sub