首页 > 解决方案 > 我的 vba 代码似乎不起作用,即使没有错误

问题描述

我正在尝试遍历指定范围内的所有单元格并替换单元格中函数的两个不同部分。

但是,代码似乎运行了,当我放一个 msgbox LastCol 时,它返回我行中的最后一个单元格,但函数没有改变。

代码:

Sub Function1()

 Dim LastCol As Integer
 Dim i As Integer

    Application.ScreenUpdating = False
     Application.DisplayAlerts = False
    With ActiveSheet
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column


    For i = 1 To LastCol

     ActiveWorkbook.Sheets("Data").Range("D3" & i).Replace "4. Apr", "5. May", xlPart
     ActiveWorkbook.Sheets("Data").Range("D3" & i).Replace "April", "May", xlPart


    Next i


End With

Application.ScreenUpdating = True
 Application.DisplayAlerts = True

标签: excelvba

解决方案


如果 i 为 1,则 Range("D3" & i) 指的是 D31。尝试,

 with ActiveWorkbook.Sheets("Data")
     .Range(.cells(3, "D"), .cells(3, LastCol)).Replace What:="4. Apr", replacement:="5. May", LookAt:=xlPart, MatchCase:=false
     .Range(.cells(3, "D"), .cells(3, LastCol)).Replace What:="April", replacement:="May", LookAt:=xlPart, MatchCase:=false
 end with

tbh,完全不清楚“指定范围”是什么意思。


推荐阅读