excel - InStr to extract all text before "[" if some cells contain "[" and some do not
问题描述
I have the following piece of code that returns a
Run-time error '5'
as soon as it comes across a cell that do not contain [
Cells(i + 2, 11) = Left(Cells(i * 2 + 1, 12), InStr(1, Cells(i * 2 + 1, 12), "[") - 1)
In this example:
Cheese[1]
is ok and returns Cheese
.
Marmite(2)[13]
is ok and returns Marmite(2)
.
Spreadable butter(13)
doesn't work.
What is the fix please
Thank you, so following on from the help below how do I incorporate and apply two IF
statements into the following?
For i = 1 To 4
If Cells(i * 2 + 2, 14) <> "" Then
Cells(i + 2, 3) = Left(Right(GetURL(Cells(i * 2 + 2, 17)), 12), 7)
Cells(i + 2, 11) = Left(Cells(i * 2 + 1, 12), InStr(1, Cells(i * 2 + 1, 12), "[") - 1)
Cells(i + 2, 12) = Left(Cells(i * 2 + 1, 13), InStr(1, Cells(i * 2 + 1, 13), "[") - 1)
End If
Next i
I am only a beginner at VBA.
解决方案
您可以检查它是否包含[ first...
Instr()
如果找不到您要查找的字符串,则该函数返回 0,因此如果没有If
首先检查该字符串的语句,您最终会得到一个 0,并且您的代码从零中减去 1 得到 -1,即不是该Left
函数的有效参数,因此您会收到错误消息。
If InStr(1, Cells(i * 2 + 1, 12), "[") > -1 Then
Cells(i + 2, 11) = Left(Cells(i * 2 + 1, 12), InStr(1, Cells(i * 2 + 1, 12), "[") - 1)
End If
这假设单元格实际上永远不会以[
如果它是第一个字符,为避免出现错误:
If InStr(1, Cells(i * 2 + 1, 12), "[") > 0 Then
Cells(i + 2, 11) = Left(Cells(i * 2 + 1, 12), InStr(1, Cells(i * 2 + 1, 12), "[") - 1)
End If
推荐阅读
- loops - 回归循环并将特定系数存储在新数据集中(Stata)
- python - 无法在 python 烧瓶中导入 MySQLdb,找不到符号:_syslog$DARWIN_EXTSN
- java - 不推荐使用 Gradle 复制命令,中断构建
- asp.net - 'SqlConnection' 未声明为 aspx 网络错误
- ios - swift中购物应用程序的加号和减号按钮
- r - R - 只允许列中的数字和点
- javascript - TamperMonkey 脚本添加的按钮仅短暂显示
- python - Keras 多标签分类损失函数:如何使用二元交叉熵获得准确的 val_acc?
- android - 可以动态创建一个 ConstraintLayout 链吗?
- javascript - 播放视频时 DIY Chrome 扩展程序没有提醒