我的代码适用于它设置的第一个单元格而不是其他单元格

时间:2016-11-22 21:02:59

标签: excel excel-vba vba

所以标题说明了一切。我已经编写了这个简短的代码来尝试获取网站URL并删除不需要的方面,以使它们对客户来说都很漂亮。然而,出于某种原因,这种我经常使用的模板这次让我失败了,只是给了皇家处理B2,这是代码中直接调用的唯一单元格。我调试很好,运行良好只是没有完成我喜欢它。没有错误使得很难辨别出问题所在。如果您有任何人可以看到这里发生的事情,请告诉我。

Sub Website()
Application.ScreenUpdating = False

Range("B2").Select

Dim TitleString As Range, cel As Range
Set TitleString = ActiveCell
Do Until IsEmpty(ActiveCell)
  For Each cel In TitleString
     If InStr(1, cel.Value, "https://") > 0 Then '
        Selection.Replace What:="https://", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
     End If

    If InStr(1, cel.Value, "http://") > 0 Then
        Selection.Replace What:="http://", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
     End If

     If InStr(1, cel.Value, "/") > 0 Then
        Selection.Replace What:="/*", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
     End If

     If InStr(1, cel.Value, "www.") > 0 Then
        Exit For

     ElseIf InStr(1, cel.Value, "www.") = 0 Then
        ActiveCell.Value = "www." & ActiveCell.Value

     Exit For
     End If

  Next cel
 ActiveCell.Offset(1, 0).Select
Loop


Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:0)

这看起来很糟糕,因为你在do循环之外设置了Int范围,所以只有一个单元要循环。你可以通过完全删除do循环来简化这一过程。而是最初将要循环的单元格声明为范围。

Integer

答案 1 :(得分:0)

任何时候使用Select it强制vba减速。

这可以避免选择和循环。

Sub Website()
Dim rng As Range
Dim ws As Worksheet

Application.ScreenUpdating = False
Set ws = ActiveSheet
Set rng = ws.Range(ws.Cells(2, 2), ws.Cells(ws.Rows.Count, 2).End(xlUp))
rng.Replace "https://", ""
rng.Replace "http://", ""
rng.Replace "/*", ""
rng.Replace "www.", ""
rng.Value = Evaluate("INDEX(""www.""&" & rng.Address & ",)")

Application.ScreenUpdating = True
End Sub

在:

enter image description here

后:

enter image description here