【发布时间】:2022-11-21 03:36:45
【问题描述】:
我有一个列,其中几乎每个单元格都由数字、字母和符号(“TS-403”或“TSM-7600”)的组合组成。我想要每一个字符不是要删除/替换为空字符串的整数,这样我只剩下数字(“403”)。
我想到了两种方法:
我认为最好的方法是创建一个包含数字 0-9 的整数数组,然后使用 for 循环遍历单元格,如果单元格中的字符串包含一个字符,则不是在数组中,则应删除该符号(而不是整个单元格)。
Sub fixRequestNmrs()
Dim intArr() as Integer
ReDim intArr(1 to 10)
For i = 0 to 9
intArr(i) = i
Next i
Dim bRange as Range
Set bRange = Sheets(1).Columns(2)
For Each cell in bRange.Cells
if cell.Value
// if cell includes char that is not in the intArr,
// then that char should be deleted/replaced.
...
End Sub()
也许第二种方法更简单,即使用 Split() 函数,因为“-”后面始终跟有数字,然后将第一个子字符串替换为“”。我对如何将 Split() 函数与范围和替换函数结合使用感到非常困惑......
For Each cell in bRange.Cells
Cells.Split(?, "-")
...
【问题讨论】:
-
如果我使用第一种方法,我会使用 scripting.dictionary 或 arraylist 的键来保存数字 0 - 9。这将允许我使用 .exists 或 .Contains 方法测试字符是否为数字分别。