为什么我的代码忽略下划线?

我正在编写一个非常简单的vba代码,用于遍历第2行中每个单元格中的字母/数字,并只保留数字。 每个单元格以4到7之间的数字开始,然后是一个字母(1或更多),a . 和一个数字,或一个下划线,一个字母和一个数字。

我遇到的问题是我的代码只是返回一些单元格的正确值。 只有有一个单元格. 正确清理。 用下划线删除_后面的所有内容,但是保留_本身,并且包含字母的单元格保留字母,但删除. 以及之后的任何事情。

这是我的代码:

 Sub getIDs() Dim counter As Integer counter = 1 Dim rowCounter As Integer rowCounter = 2 Dim original As String original = "" Dim newText As String newText = "" Do While Len(Cells(rowCounter, 2)) > 0 Do While counter <= Len(Cells(rowCounter, 2)) If Not IsNumeric((Mid(Cells(rowCounter, 2).Value, counter, 1))) Or Mid(Cells(rowCounter, 2).Value, counter, 1) = "_" Then Exit Do Else counter = counter + 1 End If Loop newText = Left(Cells(rowCounter, 2), counter) Cells(rowCounter, 2) = newText rowCounter = rowCounter + 1 Loop End Sub 

示例:原始单元格包含以下四种types的信息(数字不同):

 Input Desired output Actual output Actual output OK? ----------------|-----------------|--------------|------------------------- 12345_v2.jpg 12345 12345_ No, "_" should be removed 293847.psd 293847 293847 OK 82364382.1.tga 82364382 82364382 OK 172982C.5.tga 172982 172982C No, "C" should be removed 

所以我发现你的代码有两个问题。 第一个计数器,当你设置新的文本时,确实需要反-1,因为这是非数字或下划线字符的位置。 在柜台复制会给你一个额外的字符。

第二个问题是你需要在内部Do循环之外重置计数器variables,否则你将从前一个find的字符的位置开始。 尝试这个。

 Sub getIDs() Dim counter As Integer counter = 1 Dim rowCounter As Integer rowCounter = 2 Dim original As String original = "" Dim newText As String newText = "" Do While Len(Cells(rowCounter, 2)) > 0 counter = 1 Do While counter <= Len(Cells(rowCounter, 2)) If Not IsNumeric((Mid(Cells(rowCounter, 2).Value, counter, 1))) Or Mid(Cells(rowCounter, 2).Value, counter, 1) = "_" Then Exit Do Else counter = counter + 1 End If Loop newText = Left(Cells(rowCounter, 2), counter - 1) Cells(rowCounter, 2) = newText rowCounter = rowCounter + 1 Loop End Sub 

这将删除点和下划线。

我必须跑; 没时间去执行删除信件。 但是,这应该把你放在正确的轨道上。 我明天可以继续。

 Sub lkjhlkjh() Dim s As String Dim iUnderscore As Long Dim iDot As Long Dim iCut As Long s = Sheet1.Cells(1, 1) iUnderscore = InStr(s, "_") iDot = InStr(s, ".") If iUnderscore = 0 Then If iDot = 0 Then 'Don't cut Else iCut = iDot End If Else If iDot = 0 Then iCut = iUnderscore Else If iDot > iUnderscore Then iCut = iUnderscore Else iCut = iDot End If End If End If If iCut > 0 Then s = Left(s, iCut - 1) Sheet1.Cells(1, 1) = s End Sub