我有一個列,其中幾乎每個單元格都由數字、字母和符號(“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(?, "-")
...
uj5u.com熱心網友回復:
使用 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)
uj5u.com熱心網友回復:
如果你有這個CONCAT功能,你可以用一個相對簡單的公式來做到這一點——不需要 VBA:
=CONCAT(IFERROR(--MID(A1,SEQUENCE(LEN(A1)),1),""))
如果您更喜歡早期版本的 Excel 中的非 VBA 解決方案,可以使用更復雜的公式,但我必須回傳我的檔案才能找到它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536337.html
標籤:数组擅长VBA循环
上一篇:需要FTP檔案而不存盤解釋器檔案通過Python保存在本地
下一篇:尋找excel的公式
