【发布时间】:2014-10-05 18:18:40
【问题描述】:
我正在编写一个非常简单的 vba 代码,旨在遍历第 2 行中每个单元格中的字母/数字,并且只保留开头的数字。每个单元格以 4 到 7 个数字开头,然后是一个字母(1 个或多个)、. 和一个数字,或者一个下划线和一个字母和一个数字。
我遇到的问题是我的代码只返回了某些单元格的正确值。只有具有. 的单元格才能正确清洁。带下划线的删除_ 之后的所有内容,但保留_ 本身,带字母的单元格保留字母,但删除. 及其后面的任何内容。
这是我的代码:
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
示例:原始单元格包含这四种类型的信息(数字不同):
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
【问题讨论】:
-
请向我们展示几个说明性示例:输入、期望输出和当前代码的实际输出。
-
是不是因为你忘了重置
counter? -
我不相信你。我已经运行了你的代码,第二个和第三个中的句点像下划线和字母一样进入结果。您不会注意到它,因为您将结果输出到单元格中,并且 Excel 会为您删除尾随小数点。在您的
Left中使用counter - 1。还将内部的While替换为For。 -
我确实忘记重置计数器,将其调整为 counter-1 解决了这个问题。谢谢。