将 VBA 公式插入定义的范围

Inserting VBA formula into a defined Range

我正在遍历工作表中的 table (Sheet4) 并在每个原始列之间插入一个空列。在新的空列中,我想插入一个 VLookup 函数。

我已成功插入列,并且已在名为 FormulaRange 的变量中成功保存了正确的范围(也是正确的行数)。

我在使用 VLookup 时遇到问题。我不知道这是否是我存储变量的方式,或者我是否需要在我的 Vlookup 之后有一个粘贴功能。有人可以看一下并帮助我吗? *注意 - 我将 FormulaRange 存储为 String 因为 Range 不允许我将我的代码传递到变量中。结果我不能使用 FormulaRange.Formula 方法。

如果我要手动输入 VLookup,我会把它写成 =VLOOKUP(B1,RosettaStone_Employees!$A$1:$B$5,2,FALSE) 然后向下复制范围。

    Sub InsertColumnsAndFormulasUntilEndOfProductivityTable()
    Dim ActivityRange As Range
    Dim UserName As String
    Dim FormulaRange As String
    Dim i As Integer
    Dim x As Long
    Dim y As Long
    Dim Startrow As String
    Dim Lastrow As String

    Sheet6.Activate
    Set ActivityRange = Range("A1", Range("B1").End(xlDown))
    Sheet4.Activate
    Range("A1").Select

    y = Sheet4.Cells(Rows.Count, 1).End(xlUp).Row - 1
    x = (Sheet4.Cells(1, Columns.Count).End(xlToLeft).Column) * 2

    For i = 1 + 2 To x Step 2
        Columns(i).EntireColumn.Insert
            Startrow = 2
            Lastrow = y
            UserName = Cells(1, i - 1)
            FormulaRange = Cells(Startrow, i).Address & ":" & Cells(Lastrow + 1, i).Address
            FormulaRange = "=VLookup(UserName, ActivityRange, 2, False)"

    Next
End Sub

谢谢

乔纳森

我稍微更改了您的代码以摆脱 sheet 激活。我还更改了一些范围并包含在块中。

这是未经测试的:

Sub InsertColumnsAndFormulasUntilEndOfProductivityTable()
Dim ActivityRange As Range
Dim UserName As String
Dim FormulaRange As Range
Dim i As Long
Dim x As Long
Dim y As Long
Dim Startrow As Long
Dim Lastrow As Long

With Sheet6
    Set ActivityRange = .Range("A1", .Range("B1").End(xlDown))
End With
With Sheet4
    y = .Cells(.Rows.Count, 1).End(xlUp).Row - 1
    x = (.Cells(1, .Columns.Count).End(xlToLeft).Column) * 2

    For i = 1 + 2 To x Step 2
        .Columns(i).EntireColumn.Insert
        Startrow = 2
        Lastrow = y
        UserName = .Cells(1, i - 1) 
        Set FormulaRange = .Range(.Cells(Startrow, i), .Cells(Lastrow + 1, i))
        FormulaRange.FormulaR1C1 = "=VLookup(R1C[-1],'" & ActivityRange.Parent.Name & "'!" & ActivityRange.Address(1, 1, xlR1C1) & ", 2, False)"
        'If you do not want dynamic formulas and just want the value 
        'then comment out the above and use the below.
        'FormulaRange.Value = Application.Vlookup(UserName,ActivityRange,2,False)
    Next
End With
End Sub

R1C1 是相对命名法。当它将公式填充到列中时,它将 return 相对于要填充公式的单元格的单元格。

比如上面我用的是R1C[-1]。这表示将列的第一行直接放在左侧。因此,如果将公式输入到 B2 中,它将 return A.

其中[]表示相对地址。如果没有 [],例如 R1C1,它将表示一个绝对地址,并且会 return $A。所以 R1C1:R4C2 会 return 范围 $A:$B.