excel-vba – 将VBA公式插入定义的范围

我循环遍历工作表中的表(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

谢谢

乔纳森

最佳答案 我改变了你的代码,以摆脱表单激活.此外,我将一些内容更改为范围并包含在块中.

这是未经测试的:

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是一个相对的命名法.当它将公式填充到列中时,它将相对于将填充公式的单元格返回单元格.

例如,上面我使用R1C [-1].这表示将列的第一行直接放到左侧.因此,如果公式被输入B2,它将返回A $1.

[]表示相对地址.如果没有[]例如R1C1,它将表示绝对地址并返回$1 $.因此R1C1:R4C2将返回$A $1的范围:$B $4.

点赞