vba - 识读文档中的每个单词并将其替换为该单词的第一个字母

标签 vba ms-word cpu-word alphanumeric vba7

我正在编写一个宏,通过保留这些单词之间的所有空格并保留文本的特殊字符,仅保留文档中所有单词的首字母。

代码如下

Sub rewrite_document_with_Initials()
Set myRange = ActiveDocument.Range
Dim w As String

For Each aWord In myRange.Words
w = aWord
If IsAlphabet(w) = True Then

 aWord.Select
Set A = Selection.Range
A = Left(aWord, 1)
Selection.TypeText A & " "
Else
Debug.Print aWord

 End If
 
Next aWord
End Sub
Function IsAlphabet(inpChar As String) As Boolean
    Dim chkChar As String
    
    'Convert the character to Uppercase.
    'So that there is no need to do a check for Lower and Uppercase seperately.
    chkChar = UCase(inpChar)
    
    'Check whether input character is Alphabet or not
    IsAlphabet = Asc(chkChar) > 64 And Asc(chkChar) < 91
End Function

在上面的代码中,它会忽略文档中的每个单词并检查它是否包含字母

-如果是,则将其替换为第一个字母。

但问题是,它卡在第一个单词上,不知道我是否制作了正确的范围或字符串?

如果有最短的方法,请提出建议!

最佳答案

使用正则表达式尝试此过程。它不是每个单词,而是循环每个段落,因此,它会运行得更快。

Sub rewrite_document_with_Initials()
Dim regex As Object
Dim mColl As Object

Set regex = CreateObject("VBScript.RegExp")        
regex.Global = True
regex.IgnoreCase = True
regex.Pattern = "\B[A-Za-z]+"
'I missed special characters earlier
For i = 1 To ThisDocument.Paragraphs.Count
    ThisDocument.Paragraphs(i).Range.Text = _
        regex.Replace(ThisDocument.Paragraphs(i).Range.Text, "")
Next i
End Sub

enter image description here

关于vba - 识读文档中的每个单词并将其替换为该单词的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68313366/

相关文章:

excel - .Offset(1, 0).EntireRow.Delete 出错

java - 使用 Java 将数据发送到 Microsoft Word 文档

PHP 将数字转换为单词

vba - 通过嵌入 Excel 模板的文件以编程方式将图片设置为 powerpoint 背景

vba - Outlook 2013 - VBA - 功能区 - onLoad 未触发

vba - 从 Excel 2010 中的命令行传递参数

java - 如何让转义字符适用于 MS Word API 中的换行符?

vba - 使用 VBA 在 Word 模板中填充表格?

php - php中的字母转换

vb.net - 第一个单词小写