我想从每个单元格中删除前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 |
答案 0 :(得分:2)
这应该很容易。问题似乎是您在使用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
。)