添加列vlookup和颜色行

时间:2018-06-01 16:40:14

标签: excel vba excel-vba

我有2张工作簿 工作表Sheet1(不,主人,日期,字符串,ID,TKT) 数据(ID和名称)

我想创建一个宏,可以在数据表中添加名称和vlookup iD列,并返回名称并使用id列更改颜色

我有什么

我有2个独立的宏 1-使用id列更改颜色的宏

工作表代码

Sub ChangeColor()
lRow = Range("E" & Rows.Count).End(xlUp).Row
Set MR = Range("E2:E" & lRow)
For Each cell In MR
Select Case cell.Value
Case "x12340"
cell_colour = 2
Case "x12341"
cell_colour = 6
cell.EntireRow.Font.ColorIndex = 4
Case "x12342"
cell_colour=6 
cell.EntireRow.Font.ColorIndex = 2
Case "x12343"
cell_colour=7 
cell.EntireRow.Font.ColorIndex = 2
Case "x12344"
cell_colour=8 
cell.EntireRow.Font.ColorIndex = 2
Case "x12345"
cell_colour=9 
cell.EntireRow.Font.ColorIndex = 2
Case Else
cell_colour = 1
cell.EntireRow.Font.ColorIndex = 4
End Select
cell.EntireRow.Interior.ColorIndex = cell_colour
Next
End Sub

2-使用标题名称在Sheet1中添加列的宏 第1页

Private Sub CommandButton1_Click()
Dim rngUsernameHeader As Range
Dim rngHeaders As Range

Set rngHeaders = Range("1:1") 'Looks in entire first row.
Set rngUsernameHeader = rngHeaders.Find(what:="ID", After:=Cells(1, 1))

rngUsernameHeader.Offset(0, 1).EntireColumn.Insert
rngUsernameHeader.Offset(0, 1).Value = "Name"

End Sub

我在寻找什么

单宏可以做

1& 2,也可以从数据表(Id& name)中的sheet1中查看iL,并在sheet1中新添加的列(名称)上返回名称

=VLOOKUP(E2,Data!A:B,2,FALSE)

你能帮忙解决这个问题吗?

由于 HR

1 个答案:

答案 0 :(得分:0)

我很可能不理解您的问题,但如果您只想在rngUsernameHeader.Offset(0, 1)列中添加VLookup功能并运行更改颜色宏,则可以将Sub更改为看起来如下:

Private Sub CommandButton1_Click()
Dim rngUsernameHeader As Range
Dim rngHeaders As Range

    Set rngHeaders = Range("1:1") 'Looks in entire first row.
    Set rngUsernameHeader = rngHeaders.Find(what:="ID", After:=Cells(1, 1))

    rngUsernameHeader.Offset(0, 1).EntireColumn.Insert
    rngUsernameHeader.Offset(0, 1).Value = "Name"

    ' Add in the VLookup:
    rngUsernameHeader.Offset(1, 1).Formula = "=VLOOKUP(E2,Data!A:B,2,FALSE)"

    ' Run the ChangeColor Macro:
    ChangeColor

End Sub

希望有助于您朝着正确的方向前进。