在Created列中添加您不知道列值的公式

时间:2018-01-24 16:40:13

标签: excel vba excel-vba

我在Excel中执行了一个查找特定值的find函数,并在右边插入了一个新的2个位,因为这个值可以在任何地方,我不确定列值(A,B,C, D等。如果我不确定该值,如何为这个新创建的列添加公式?

这是我到目前为止所做的:

 With Range("A1:Z1")
    Set rFind = .Find(What:="US", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not rFind Is Nothing Then
        lastColumn = rFind.Column
    Columns(lastColumn + 2).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range((lastColumn + 2) & LR).Formula = "=(5)"
    End If

2 个答案:

答案 0 :(得分:1)

我的回答:

Sub test()

With Range("A1:Z1")
    Set rFind = .Find(What:="US", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not rFind Is Nothing Then
        lastColumn = rFind.Column
    Columns(lastColumn + 2).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range(Cells(1, (lastColumn + 2)), Cells(123, (lastColumn + 2))).Formula = "=(5)"
    End If
End With

End Sub

将123替换为最后一行。

根据多个条件查找请求(要求“美国”和“新价格”在同一列中):

Sub test()

    lastColumn = Evaluate(" Match(""US"" & ""New Price"", A1:Z1 & A2:Z2, 0)")
    Columns(lastColumn + 2).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range(Cells(1, (lastColumn + 2)), Cells(123, (lastColumn + 2))).Formula = "=(5)"

End Sub

如果描述了问题:

Sub test2()

Dim rng As Range

With Range("A1:Z1")
    Set rFind = .Find(What:="US", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not rFind Is Nothing Then
        lastColumn = rFind.Column
    End If
End With

Set rng = Range(Cells(2, lastColumn), Cells(2, lastColumn + 7))

final_Column = Application.Match("New Price", rng, 0)

lastColumn = lastColumn + final_Column

Columns(lastColumn + 2).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range(Cells(1, (lastColumn + 2)), Cells(123, (lastColumn + 2))).Formula = "=(5)"


End Sub

答案 1 :(得分:0)

以下将放置该公式(在示例中,它将在F列中),返回列D查找关键字:

rFind.Offset(0, 2).Formula = "=VLOOKUP(RC[-2],'[ABC.xlsx]Sheet1'!C1,1,FALSE)"

PS。 C1并不是一个可以执行VLOOKUP的表格,但没关系......