Excel 返回/char Vba宏之前的值

Excel 返回/char Vba宏之前的值,excel,vba,Excel,Vba,我有很多名字,有些有/char,有些没有 因此,我需要将/单元的名称复制到一个新列中 我的数据不超过300个 我的意思不是一个特定的范围。。有时多有时少 我尝试了这段代码,但不是对所有的项目都有效,也不是很好 你能给我一些建议吗 Dim str1 As String Dim str2 As String str1 = Range("B2").Value x = 1 Do Until str2 = "/" If x = Len(str1) + 2 Th

我有很多名字,有些有/char,有些没有 因此,我需要将/单元的名称复制到一个新列中

我的数据不超过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

分裂单元
  • 如评论中所述,这可以通过各种方式更有效地完成
  • 这是一个介绍性代码,说明了各种主题:
    • 使用显式选项(声明所有变量)
    • 使用常量
    • 计算列中最后一个“已占用”行
    • 为…下一个循环使用
    • 使用范围单元格
    • 并使用诸如
      Instr
      Trim
      Left
      Right
      等文本功能
  • “*
    表示两个代码之间的唯一区别。为了简化,您可以将两行代码从第二行适当地复制到第一行代码
代码

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

请注意,这可以通过一个简单的公式来完成,不需要VBA。VBA是必要的吗?
Goto OUT
可以替换为
Exit Do
<代码>=IFERROR(TRIM(LEFT(B1,FIND(“/”,B1)-1)),B1)谢谢@BigBen,是的,因为这只是第一部分,我会做REST,然后使用VBA编写@DarrenBartrup Cook提供的整个范围的公式。看来你现在的尝试是把事情复杂化了。