簡體   English   中英

InStr 提取“[”之前的所有文本,如果某些單元格包含“[”而某些單元格不包含

[英]InStr to extract all text before “[” if some cells contain “[” and some do not

我有以下代碼返回一個

運行時錯誤“5”

一旦遇到不包含[

Cells(i + 2, 11) = Left(Cells(i * 2 + 1, 12), InStr(1, Cells(i * 2 + 1, 12), "[") - 1)

在這個例子中:
Cheese[1]可以並返回Cheese
Marmite(2)[13]沒問題並返回Marmite(2)
Spreadable butter(13)不起作用。

請問有什么解決辦法


謝謝,那么根據下面的幫助,我如何將兩個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

我只是 VBA 的初學者。

您可以檢查它是否包含[ first...

如果找不到您要查找的字符串,則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

這假設單元格實際上永遠不會以[

如果它是第一個字符,為避免出現錯誤:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM