首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在VBA中使用宏处理空单元格?

如何在VBA中使用宏处理空单元格?
EN

Stack Overflow用户
提问于 2018-01-08 22:20:25
回答 1查看 298关注 0票数 0

我想从每个单元格中删除前4个字符。在我的代码中,我首先查看最后一行是什么,然后告诉程序运行到这一点。只有在选定的列中没有空单元格时,它才起作用。如果有空单元格,程序会在第一个空单元格停止。我试过一些循环,但从来没成功过。

下面是我的代码:

代码语言:javascript
运行
复制
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

以下是一些数据:

代码语言:javascript
运行
复制
|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 |
EN

Stack Overflow用户

发布于 2018-01-08 23:04:11

这应该很容易。问题似乎是在使用Right时,您试图返回值<= 0。您可以采用以下几种方法:

代码语言:javascript
运行
复制
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)。

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48152214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档