按标题名称查找列,并使用数组项

时间:2016-10-05 11:02:45

标签: excel vba excel-vba

我被要求创建一个工具,允许我使用查找用文本值替换数值,查找值来自工作表(“lookupSheet”,用于此问题的目的),并且用于替换另一个工作表中的数值(“replaceSheet”,为了这个问题的目的。)所以,如果0 =狗,1 =猫,2 =牛,3 =绵羊我的原始列看起来像:

NewCol
0
1
2
3
1
0

然后,在查找范围上运行之后,它应该是:

NewCol
Dog
Cat
Cow
Sheep
Cat
Dog

查找值始终按其对应的数字顺序排列,因此很容易将其传递给数组。但是,一个问题是列标题保持不变,但可能会改变其在不同工作表中的位置,所以我试图调整有效的代码,因此它将首先按名称找到标题(“NewCol”,用于获取列引用,然后应用循环将值更改为此。但是,每次我在代码中进入循环时,都会得到一个应用程序定义或对象定义的错误,我不确定它是什么,我做错了。我在“lRow =”行上设置了一个断点,之后是错误发生时。

Sub ChangeCol()

Dim strArray As Variant
Dim TotalRows As Long
Dim replaceSheet As Worksheet
Dim lookupSheet As Worksheet
Dim I As Long
Dim lRow As Long
Dim aCell As Long

    'Set worksheets
    Set lookupSheet = ThisWorkbook.Sheets(1)
    Set replaceSheet = ThisWorkbook.Sheets(2)

    'Load lookupArray
    TotalRows = lookupSheet.Rows(Rows.Count).End(xlUp).Row
    strArray = lookupSheet.Range(Cells(2, 2), Cells(TotalRows, 2)).Value
    MsgBox "Loaded " & UBound(strArray) & " items!"

    'Find column to replace values
    aCell = replaceSheet.Range("A1:DD1").Find(What:="NewCol", LookIn:=xlValues, LookAt:=xlWhole, _
    MatchCase:=False, SearchFormat:=False).Column

    lRow = replaceSheet.Cells(Rows.Count, aCell).End(x1Up).Row

    'Loop through lookup array and replace values
    For I = 1 To UBound(strArray)
        replaceSheet.Columns(aCell).replace What:=(I - 1), Replacement:=strArray(I, 1), LookAt:=xlWhole, MatchCase:=True
    Next I

End Sub

我不确定它出了什么问题,或者如果有更好的解决方法,我会非常感谢您对我出错的地方提供任何帮助。

1 个答案:

答案 0 :(得分:2)

正如评论中所指出的那样,你有一个拼写错误:lRow = replaceSheet.Cells(Rows.Count, aCell).End(x1Up).Row它是xLUp1更改为l

使用范围进行一些更改,并避免使用替换数组来简单地按照您已按顺序放置值:

Sub ChangeCol()

Dim strArray As Variant
Dim TotalRows As Long
Dim replaceSheet As Worksheet
Dim lookupSheet As Worksheet
Dim I As Long
Dim lRow As Long
Dim ColToCopy As Long
Dim MatchedHeader As Range
Dim ZoneToFill As Range

    'Set worksheets
    Set lookupSheet = ThisWorkbook.Sheets(1)
    Set replaceSheet = ThisWorkbook.Sheets(2)

    'Load lookupArray
    ColToCopy = 2
    TotalRows = lookupSheet.Cells(lookupSheet.Rows.Count, ColToCopy).End(xlUp).Row
    strArray = lookupSheet.Range(Cells(2, ColToCopy), Cells(TotalRows, ColToCopy)).Value
    MsgBox "Loaded " & UBound(strArray) & " items!"

    'Find column to replace values
    Set MatchedHeader = replaceSheet.Range("A1:DD1").Find(What:="NewCol", LookIn:=xlValues, LookAt:=xlWhole, _
                        MatchCase:=False, SearchFormat:=False)

    lRow = replaceSheet.Cells(replaceSheet.Rows.Count, MatchedHeader.Column).End(xlUp).Row

    'Resize the range to fit the array and send the values in
    MatchedHeader.Offset(1, 0).Resize(UBound(strArray, 1), UBound(strArray, 2)).Value = strArray

End Sub