【问题标题】:Macro not moving the string after the character found找到字符后宏不移动字符串
【发布时间】:2017-05-26 13:41:50
【问题描述】:

如果字符串中包含 @ 字符,我正在尝试将单元格值移动到相邻单元格。但以下宏未按预期工作。

Sub Macro1()
  Dim MatchString As String
  MatchString = "@"
  For Counter = 1 To Range("A:A").Count
    If (InStr(Range("A" & Counter).Value, Len(MatchString)) = MatchString) Then
      Range("A" & Counter).Select
      Selection.Cut
      Range("B" & Counter).Select
      ActiveSheet.Paste
    End If
  Next Counter
End Sub

请建议我在这个宏中遗漏了什么,以便我的程序运行良好。

【问题讨论】:

  • 你在寻找"(If ISCunable to resolve,"而不是"@"
  • 哎呀需要编辑...仍然无法正常工作
  • 您也只查看左侧字符是否为@,而不是字符串是否包含@
  • If "myCell.Value" Like "*@*" Then 也很有帮助。看here
  • 现在您尝试在带有InStr(Range("A" & Counter).Value, Len(MatchString)) 的字符串中查找1 删除Len(),因为它返回了字符串长度的数字。 InStr(MatchString,Range("A" & Counter).Value)。请研究每个部分的作用以及如何使用它,我们不是维基百科。

标签: vba excel


【解决方案1】:

这应该有效;使用 Like

Sub Macro1()

  With ActiveSheet
  For Counter = 1 To .Range("A:A").Count
    If .Range("A" & Counter).Value Like "*@*" Then

      .Range("A" & Counter).Cut .Range("B" & Counter)
      Application.CutCopyMode = False

    End If
  Next Counter
  End With

End Sub

您应该避免在 VBA 中选择/激活:

How to avoid using Select in Excel VBA macros

如果您真的不想遍历整个列,请阅读以下内容:

EXCEL VBA - Loop through cells in a column, if not empty, print cell value into another column

作为另一个答案发布,Find 将是解决此问题的好方法(更快)。

【讨论】:

  • 谢谢。真的很有帮助。
  • ++ 完美答案。只是添加,剪切/复制后添加Application.CutCopyMode = False。无害。 :)
【解决方案2】:

然后查看 A 列中的每个单元格,只需使用 FIND 直接转到单元格。

每次找到 @ 时,它将被移到 B 列,并删除 A 列中的值。当找不到更多内容时,循环将停止。

Public Sub MoveToAdjactent()

    Dim MatchString As String
    Dim rFound As Range

    MatchString = "@"

    With ThisWorkbook.Worksheets("Sheet1").Columns(1)
        Set rFound = .Find(MatchString, LookIn:=xlValues, LookAt:=xlPart)
        If Not rFound Is Nothing Then
            Do
                rFound.Offset(, 1) = rFound
                rFound.ClearContents
                Set rFound = .FindNext(rFound)
            Loop While Not rFound Is Nothing
        End If
    End With

End Sub

【讨论】:

  • 你应该这样做。循环是不好的做法。 +1
猜你喜欢
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 2022-10-12
  • 2013-12-13
  • 2021-10-06
  • 2014-05-09
  • 2019-04-26
  • 1970-01-01
相关资源
最近更新 更多