excel - 返回 / 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
解决方案
拆分单元格
- 正如评论中提到的,这可以通过各种方式更有效地完成。
- 这是说明各种主题的介绍性代码:
- 使用
Options Explicit
(声明所有变量), - 使用常量,
- 计算列中最后一个“占用”行,
- 使用一个
For...Next Loop
, - 使用
Range.Cells
, - 并使用文本函数,如
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
推荐阅读
- javascript - 如何在 Heroku 上发现我的内部和外部 IP 地址?
- android - React Native ./gradlew bundleRelease 或 assembleRelease 命令无限加载
- python - 如何为python 2.7创建虚拟环境
- rust - 如何验证结构中的选项参数值
- python - 更改 Statsmodel 的自由度
- php - 以form提交Textarea的内容?
- java - MediaPlayer.setDataSource() 的演示?
- python - 在 wxPython 中编写联系表格?
- php - PHP PDO 参数查询在包含子查询时失败
- php - 如何设置默认密码