[英]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'
运行时错误“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
. Cheese[1]
可以并返回Cheese
。
Marmite(2)[13]
is ok and returns Marmite(2)
. Marmite(2)[13]
没问题并返回Marmite(2)
。
Spreadable butter(13)
doesn't work. Spreadable butter(13)
不起作用。
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?谢谢,那么根据下面的帮助,我如何将两个
IF
语句合并并应用到以下语句中?
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.我只是 VBA 的初学者。
You can just check to see if it contains a [ first...您可以检查它是否包含[ first...
The Instr()
function returns a 0 if the string you are looking for cannot be found, so without an If
statement to check for that first, you end up with a 0, and your code is subtracting 1 from the zero to get -1, and that is not a valid argument for the Left
function, so you get the error.如果找不到您要查找的字符串,则
Instr()
function 返回 0,因此如果没有If
语句首先检查该字符串,您最终会得到一个 0,并且您的代码从零中减去 1 得到 -1 ,这不是Left
function 的有效参数,因此您会收到错误消息。
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
This assumes the cell will never actually start with a [这假设单元格实际上永远不会以[
To avoid getting an error if it IS the first character:如果它是第一个字符,为避免出现错误:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.