我想从每个单元格中删除前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 |发布于 2018-01-08 23:04:11
这应该很容易。问题似乎是在使用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)。
https://stackoverflow.com/questions/48152214
复制相似问题