excel 插入新的表列以包括以前列的IFELSE结果

bybem2ql  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(106)

包含精品店编号的L列和包含精品店代码的新插入列的AB列。
正如我的标题所示,我希望向一个表中添加一个新列,该表包含来自前一列的IF ELSE值(列L,包含值A、B、C、D、E,具体取决于精品店)。

Sub BoutiqueCodes()
Dim tbl As ListObject
Dim cel As Range
Dim boutique As String[enter image description here][1]
Dim codes As Integer
boutique = Range("L, L").Value
'the boutique values come from Column L
    Set tbl = ActiveSheet.ListObjects("Table_1")
    With tbl
        .ListColumns.Add.Name = "Code"
        For Each cel In .ListColumns("Code").DataBodyRange.Cells
            If boutique = "A" Then
                codes = 506
             ElseIf boutique = "B" Then
                codes = 606
            ElseIf boutique = "C" Then
                codes = 706
            ElseIf boutique = "D" Then
                codes = 611
            ElseIf boutique = "E" Then
                codes = 612
            Else
                codes = 0
            End If
            cel.Value = codes
        Next
    End With
End Sub

我在boutique = Range("L, L").Value行出错了。我确信这一点。我想在新列中的是精品店的相应代码。以前,我没有boutique = Range("L, L").Value行,但我所有的代码值都是0。任何帮助都是很好的。谢谢

6l7fqoea

6l7fqoea1#

通过计算向表中添加列

使用Offset的快速修复

Option Explicit

Sub BoutiqueCodes()
    Dim tbl As ListObject
    Dim cel As Range
    Dim boutique As String
    Dim codes As Long
    Dim ColumnOffset As Long
    Set tbl = ActiveSheet.ListObjects("Table_1")
    With tbl
        .ListColumns.Add.Name = "Code"
        ColumnOffset = .ListColumns("Boutique").Index _
                     - .ListColumns("Code").Index
        For Each cel In .ListColumns("Code").DataBodyRange.Cells
            boutique = cel.Offset(, ColumnOffset).Value
            If boutique = "A" Then
                codes = 506
            ElseIf boutique = "B" Then
                codes = 606
            ElseIf boutique = "C" Then
                codes = 706
            ElseIf boutique = "D" Then
                codes = 611
            ElseIf boutique = "E" Then
                codes = 612
            Else
                codes = 0
            End If
            cel.Value = codes
        Next
    End With
End Sub

相关问题