首页 > 解决方案 > 返回 / char Vba 宏之前的值

问题描述

我有很多名字,其中一些有 / 字符,而一些没有,所以我需要将 / 的名称单元复制到新列

我的数据不限制超过 300 我的意思不是特定范围.. 有时更多有时更少

我尝试此代码,但不适用于所有项目并且不太好请提供任何建议

Dim str1 As String
Dim str2 As String



str1 = Range("B2").Value
x = 1
Do Until str2 = "/"
If x = Len(str1) + 2 Then GoTo OUT
str2 = Mid(str1, x, 1)
x = x + 1
Loop
OUT:
Range("E2").Value = Left(str1, x - 2)
End Sub

数据示例

标签: excelvba

解决方案


拆分单元格

  • 正如评论中提到的,这可以通过各种方式更有效地完成。
  • 这是说明各种主题的介绍性代码:
    • 使用Options Explicit(声明所有变量),
    • 使用常量,
    • 计算列中最后一个“占用”行,
    • 使用一个For...Next Loop
    • 使用Range.Cells,
    • 并使用文本函数,如InstrTrimLeftRight.
  • '*表示两个代码之间的唯一区别。为简化起见,您可以适当地将第二行代码复制到第一行代码。

编码

Option Explicit

Sub getName()
    
    Const FirstRow As Long = 2
    Const Delimiter As String = "/"
    
    Dim LastRow As Long: LastRow = Cells(Rows.Count, "B").End(xlUp).Row
    
    Dim sString As String
    Dim Pos As Long
    Dim i As Long
    
    For i = FirstRow To LastRow
        sString = Cells(i, "B").Value
        Pos = InStr(1, sString, Delimiter)
        If Pos > 0 Then
            Cells(i, "E") = Trim(Left(sString, Pos - 1)) '*
        Else
            Cells(i, "E") = Trim(sString) '*
        End If
    Next i
    
End Sub

Sub getLastName()
    
    Const FirstRow As Long = 2
    Const Delimiter As String = "/"
    
    Dim LastRow As Long: LastRow = Cells(Rows.Count, "B").End(xlUp).Row
    
    Dim sString As String
    Dim Pos As Long
    Dim i As Long
    
    For i = FirstRow To LastRow
        sString = CStr(Cells(i, "B").Value)
        Pos = InStr(1, sString, Delimiter)
        If Pos > 0 Then
            Cells(i, "F") = Trim(Right(sString, Len(sString) - Pos)) '*
        Else
            Cells(i, "F") = "" '*
        End If
    Next i
    
End Sub

推荐阅读