【问题标题】:Deleting instances of chars using arrays and loops使用数组和循环删除字符实例
【发布时间】: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 方法测试字符是否为数字分别。

标签: arrays excel vba loops


【解决方案1】:

使用 Like 运算符将数字转换为整数

功能

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns an integer composed from the digits of a string.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function DigitsToInteger(ByVal SearchString As String) As Long

    Dim ResultString As String
    Dim Char As String
    Dim n As Long
    
    For n = 1 To Len(SearchString)
        Char = Mid(SearchString, n, 1)
        If Char Like "[0-9]" Then ResultString = ResultString & Char
    Next n
    
    If Len(ResultString) = 0 Then Exit Function

    DigitsToInteger = CLng(ResultString)

End Function

工作表示例

Sub DigitsToIntegerTEST()

    Const FIRST_ROW As Long = 2

    ' Read: Reference the (single-column) range.
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
    
    Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
    If LastRow < FIRST_ROW Then Exit Sub ' no data
    
    Dim rg As Range: Set rg = ws.Range("B2", ws.Cells(LastRow, "B"))
    Dim rCount As Long: rCount = rg.Rows.Count
    
    ' Read: Return the values from the range in an array.
    
    Dim Data() As Variant
    
    If rCount = 1 Then
        ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
    Else
        Data = rg.Value
    End If
    
    ' Modify: Use the function to replace the values with integers.
    
    Dim r As Long
    
    For r = 1 To rCount
        Data(r, 1) = DigitsToInteger(CStr(Data(r, 1)))
    Next r
    
    ' Write: Return the modifed values in the range.
    
    rg.Value = Data
    ' To test the results in the column adjacent to the right, instead use:
    'rg.Offset(, 1).Value = Data

End Sub

在 VBA 中(简单)

Sub DigitsToIntegerSimpleTest()
    Const S As String = "TSM-7600sdf"
    Debug.Print DigitsToInteger(S) ' Result 7600
End Sub

在 Excel 中

=DigitsToInteger(A1)

【讨论】:

  • 有用的方法 +:) ... Fyi 你可能会通过棘手的匹配@VBasic 对我的替代方案感兴趣
【解决方案2】:

如果你有 CONCAT 函数,你可以用一个相对简单的公式来做到这一点——不需要 VBA:

=CONCAT(IFERROR(--MID(A1,SEQUENCE(LEN(A1)),1),""))

如果您更喜欢早期版本的 Excel 中的非 VBA 解决方案,可以使用更复杂的公式,但我必须返回我的文件才能找到它。

【讨论】:

  • 一种优雅而有用的方式+:)
【解决方案3】:

一个棘手的功能GetVal()

下面的函数

  • 通过帮助函数String2Arr()将字符串翻译成单个字符数组arr
  • 通过巧妙地执行 Application.Match 将它们分为数字(类别代码 6)或非数字类别(其他)(这里没有它的第三个参数,主要用于精确搜索,并通过比较两个数组)
  • 通过Instr()找到原字符串中的起始位置
  • 通过Val() 返回右子串的值(~> 见注释)。
Function GetVal(ByVal s As String) As Double
    Dim arr:      arr = String2Arr(s):      Debug.Print Join(arr, "|")
    Dim chars:    chars = Split(" ,',+,-,.,0,A", ",")
    Dim catCodes: catCodes = Application.Match(arr, chars)  'No 3rd zero-argument!!
    Dim tmp$:     tmp = Join(catCodes, ""): Debug.Print Join(catCodes, "|")
    Dim pos&:     pos = InStr(tmp, 6)   ' Pos 6: Digits; pos 1-5,7: other symbols/chars
    GetVal = Val(Mid(s, pos))           ' calculate value of right substring
End Function

笔记

Val 函数可以将具有起始数字的(子)字符串转换为数字,即使后面有非数字字符也是如此。

帮助功能String2Arr()

将字符串原子化为单个字符数组:

Function String2Arr(ByVal s As String)
    s = StrConv(s, vbUnicode)
    String2Arr = Split(s, vbNullChar, Len(s)  2)
End Function

调用示例

    Dim s As String
    s = "aA+*&$%(y#,'/)!-12034.56blabla"
    Debug.Print GetVal(s)          ' ~~> 12034.56

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2015-12-07
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多