[英]How can I handle empty Cells with my macro in VBA?
我想從每個單元格中刪除前4個字符。 在我的代碼中,我首先查看最后一行是什么,然后告訴程序運行到這一點。 僅在所選列中沒有空單元格的情況下才有效。 如果有空的,程序將在第一個空單元格處停止。 我嘗試了一些循環,但從未成功...
這是我的代碼:
Sub datei_format_prefix()
Dim Zelle As Range
Dim bCell As Range
find_last_row
For Each bCell In Selection
Range(bCell.Address).Select
Range(bCell.Address).Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
For Each Zelle In Selection
If Zelle.Value Like "*_*" Then
Zelle.Value = Right(Zelle, Len(Zelle) - 4)
End If
If Zelle.Value Like "?########" Then
Zelle.Value = Right(Zelle, Len(Zelle) - 1)
End If
Next
Next
End Sub
Sub find_last_row()
Dim rownum As Integer
Dim SelRange As Range
Set SelRange = Selection
Range("A2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
rownum = Selection.Row + Selection.rows.Count - 1
MsgBox rownum
SelRange.Select
End Sub
一些數據:
|This is Row 1 of Excel Sheet with some Buttons in it|
| Heder1 | Header2 | Header3 |
|--------------|------------|--------------|
| JFG_12345678 | Production | ABC_12345678 |
| JFG_12345678 | Production | ABC_12345678 |
| JFG_12345678 | Production | ABC_12345678 |
| JFG_12345678 | Production | |
| | Production | ABC_12345678 |
| | Production | |
| JFG_12345678 | Production | ABC_12345678 |
那應該很容易。 問題似乎是您在嘗試使用Right
時嘗試返回小於等於0的值。 您可以采取幾種方法:
For Each Zelle In Selection
Dim ZelleValue As Variant
ZelleValue = Zelle.Value
'If ZelleValue <> vbNullString Then ' If Cell Isnt Blank.
'This is what you're asking for, but will still allow errors.
If Not IsError(ZelleValue) Then
If Len(ZelleValue > 1) Then
If Len(ZelleValue) > 4 Then
If ZelleValue Like "*_*" Then
Zelle.Value = Right(ZelleValue, Len(ZelleValue) - 4)
End If
End If
If ZelleValue Like "?########" Then
Zelle.Value = Right(ZelleValue, Len(ZelleValue) - 1)
End If
End If
End If
Next
請注意,我添加了檢查空白單元格的條件,但將其注釋掉。 原因是您確實應該檢查單元格的長度是否符合預期。 例如,如果您嘗試使用小於零的值作為向右或向左的參數,則會收到錯誤消息。 為了避免這種情況,我們確保在調用這些條件之前可以返回Len(ZelleValue) - 4)
和Len(ZelleValue) - 1
。 反過來,我們將跳過空格以及不符合期望值的單元格(例如"f_o"
, Like "*_*"
但Len("f_o") - 4
等於-1
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.