我有一列像XXX US一样的东西,我想为细胞返回XXX。我想制作一个宏,只需点击一下即可删除整个列。出于某种原因,我的代码中的代码部分会引发错误,但是当我不使用循环时它会起作用。我有什么可以做的吗?
Sub DEAS()
Dim cellText As String
Dim ticker As String
Dim i As Integer
i = 5
Do While i < 8000
cellText = Cells(i, 1).Value
ticker = Left(cellText, InStr(cellText, " ") - 1)
Cells(i, 1).Value = ticker
i = i + 1
Loop
End Sub
答案 0 :(得分:0)
尝试一下:
Sub DEAS()
Dim cellText As String
Dim ticker As String
Dim i As Integer
i = 5
Do While i < 8000
cellText = Cells(i, 1).Value
If InStr(cellText, " ") > 0 Then
Cells(i, 1).Value = Split(cellText, " ")(0)
End If
i = i + 1
Loop
End Sub
答案 1 :(得分:0)
Left(cellText, InStr(cellText, " ") - 1)
不包含空格, cellText
将抛出错误5“无效的过程调用或参数”。这很可能是由于遇到A5:A8000中某个值不是预期格式或为空的值。在这种情况下,Instr
将返回0,这会使您的通话评估为Left(cellText, -1)
。您需要首先检查返回值(请注意,您还可以使用For
循环 - 当您的条件修复时,IMHO更具可读性):
Sub DEAS()
Dim cellText As String
Dim ticker As String
Dim i As Integer
Dim pos As Integer
For i = 5 To 8000
cellText = Cells(i, 1).Value
pos = InStr(cellText, " ")
If pos > 0 Then
ticker = Left(cellText, pos - 1)
Cells(i, 1).Value = ticker
End If
Next i
End Sub