删除部分string

我有这个代码,这是90-95%的时间,但有一段时间,它只会删除部分,我想删除。

While InStr(fnd, SCHFR) <= 0 And c <= 300 c = c + 1 fnd = Sheet1.Cells(c, 8) Wend If c >= 300 Then Sheet2.Cells(r, cmn) = "Not found" Else cleanup = InStr(1, fnd, ": ") finalString = Right(fnd, Len(fnd) - cleanup - 1) Sheet2.Cells(r, cmn) = finalString End If scnm = scnm + 1 cmn = cmn + 1 c = 1 Wend 

scnm只是跟踪我们正在寻找的string来清理它的计数器。 SCHFR是这样定义的:

 Select Case scnm Case 1 SCHFR = "First Name:" Case 2 SCHFR = "Last Name:" Case 3 SCHFR = "Phone:" Case 4 SCHFR = "Seconday Phone:" Case 5 SCHFR = "Email:" Case 6 SCHFR = "SecondaryEmail:" Case 7 SCHFR = "Country:" End Select 

结果会像“名字:莎拉”一样回来,我想删除“名字:”部分,所以它只是“萨拉”,但偶尔我会得到一个像“第一个名字:萨拉” ,而周围的所有其他人是正确的。

为什么不使用InStr查找:的索引,然后使用它来删除该位置左侧的所有内容。

示例数据:

在这里输入图像说明

 Sub SomeSub() Dim MyRange As Range Dim index As Integer Dim CellValue As String Dim CapturedValue As String Set MyRange = ThisWorkbook.ActiveSheet.UsedRange.Columns(1) For Each cell In MyRange.Cells CellValue = cell.Value ' +1 caters for the sapce between the : and then data index = InStr(1, CellValue, ":") + 1 If Len(CellValue) > index Then CapturedValue = Right(CellValue, Len(CellValue) - index) Else 'No Data has been inseted after the : CapturedValue = "" End If cell.Value = CapturedValue Next cell End Sub 

这个简单的代码对我来说很好(假设你在A列有“名字:Sarah”,在B列只显示“Sarah”):

 Sub remove_until() Dim i, lrowA, remChar As Long Dim mString As String lrowA = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row For i = 1 To lrowA mString = Cells(i, 1).Value remChar = InStr(mString, ":") + 1 Cells(i, 2).Value = Right(mString, Len(mString) - remChar) Next End Sub