vba - 字符串中的通配符

标签 vba excel

我有一个定期收到的电子表格,其中包含大量包含姓名的单元格。有些单元格有一个全名,包括中间首字母和句点。

例如:

Springer, Jerry A.

虽然我收到的表格时不时会有以下内容:

Springer, Jerry .

我需要去掉那些中间的缩写,但还要检查以确保我只是删除了“.”。如果它在那里的话。

请原谅我缺乏正确的逻辑,但我有以下 ca-ca 子:

Sub DeleteMiddleI()
Dim nr1, nr2 As Range
Dim col As Integer

col = 1
Set nr1 = Cells(65536, col).End(xlUp)
Set nr2 = Cells(col, 1)

Do While nr2 <> nr1
    'Check to be sure the cell isn't empty
    If Len(nr2) <> 0 Then
         'Check to see if the last character is a "."
         If Right$(nr2, 1) = "." Then
            'Check and be sure there is a character before the "."
            If InStr(1, nr2.Text, "[A-Z].") > 0 Then '<<<<<<CODE BREAKAGE
                nr2 = Left$(nr2, Len(nr2) - 3)
            End If
         End If
    End If

    col = col + 1
    Set nr2 = Cells(col, 1)
Loop

End Sub

它打破了

If InStr(1, nr2.Text, "[A-Z].") > 0 Then

我觉得自己很蠢……但我错过了什么?

最佳答案

这会有帮助吗?这将取代所有的“.”。什么都没有。

Option Explicit

Sub Sample()
    Sheets("Sheet1").Cells.Replace What:=" .", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End Sub

编辑

删除缩写部分是什么意思?您的意思是将 Springer, Jerry A. 更改为 Springer, Jerry 或将 Springer, Jerry . 更改为 Springer, Jerry

如果是,那么这会有帮助吗?

Option Explicit

Sub Sample()
    Dim LastRow As Long
    Dim Pos As Long, i As Long

    With Sheets("Sheet1")
        LastRow = .Range("A" & Rows.Count).End(xlUp).Row

        For i = 1 To LastRow
            Pos = InStr(1, .Range("A" & i).Value, ", ") + 2
            If Pos > 2 Then
                Pos = InStr(Pos, .Range("A" & i).Value, " ")
                If Pos > 0 Then .Range("A" & i).Value = Mid(.Range("A" & i).Value, 1, Pos - 1)
            End If
        Next i
    End With
End Sub

关于vba - 字符串中的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10453853/

相关文章:

excel - 通过 VBA 将文档上传到 SharePoint

excel - Excel 2013 VBA 编辑器中的引用呈灰色

sql - VBA快速将许多记录插入 Access 数据库

javascript - VBA:查找并更新 HTML 表单中的输入字段

vba - 使用 VBA 的图表绝对位置

c# - 数据表上的 LINQ 查找所有行都为空的位置

python - 从Dataframe对象过滤字符串和整数值-python

C# Visual Studio Excel 加载项 : How can I detect Excel Office Theme Change?

vba - 当我使用 "Professional Excel Development"书中的错误处理方法时如何调试?

php - 这应该很容易,但我无法弄清楚