在Excel VBA宏中,如何迭代大量列?

时间:2017-01-16 08:57:28

标签: excel-vba loops vba excel

我有以下Excel工作表和VBA宏,它将AY,AZ,BA列上的每个x替换为单元格AY1,AZ1,BA1的值:

Excel sheet

macro

如您所见,我的脚本的列名称是硬连线的。我有很多列(约300)。如何使我的脚本自动将列索引增加1 /遍历多列?

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

Sub ReplaceValues()

Dim myRng, myColumn As Range

Set myRng = Range("A:C").Columns ' <- this is you range, change A:C as needed

For Each myColumn In myRng '<- this will loop through each column in your range

    myColumn.EntireColumn.Replace What:="x", Replacement:=Cells(1, myColumn.Column).Text, LookAt:=xlWhole, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
Next

End Sub

答案 1 :(得分:0)

我还找到了另一种工作方法,最终由我自己完成:

Dim col As Integer

For col = 8 To 300
    Columns(col).Replace What:="x", Replacement:=Cells(1, col).Text, LookAt:=xlWhole, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
Next