Word VBA 宏不保留特殊字符

问题描述 投票:0回答:1

我有一个生成输入收件箱的宏,我在其中键入文本,然后将其附加到 Word 文档中

但是,如果我在此框中输入特殊字母/字符,则不会考虑它们

示例:如果我输入“Dziękuję”,“ę”将被替换为常规“e”

有没有办法更新我的代码以使其接受这些类型的字符?

Sub WriteEngravingText()
WriteEngravingText Macro
Dim shp As Shape
Dim engravingL1 As String
Dim engravingL2 As String
Dim fontName As String
Dim filePath As String

For Each shp In ActiveDocument.Shapes
    
    If shp.Type = msoTextBox Then
        shp.Select
        Selection.WholeStory
        engravingL1 = InputBox("First line : ", "Write")
        Selection.TypeText Text:=engravingL1
        Selection.TypeParagraph
        engravingL2 = InputBox("Second line: ", "Write")
        Selection.TypeText Text:=engravingL2
        fontName = InputBox("Font name : ", "Write")
        Selection.WholeStory
        Selection.Font.Name = fontName
        Selection.Font.Size = 11
        filePath = InputBox("File path : ", "Write")
        ActiveDocument.SaveAs fileName:=filePath
        Exit For
    End If
    
Next
End Sub
vba ms-word
1个回答
0
投票

问题不在于VBA本身,即使VBA IDE无法显示这些字符,它也会正确处理它们。您的问题是

InputBox
命令无法处理不属于计算机代码页的字符。我还没有使用不同的系统区域设置设置(如 Piemol 在评论中或在此网页上提供的 SO-Link 中所述),但我强烈假设一旦您将此设置更改为代码页面包含“ę”,将返回正确的字符。

但是,这只能部分解决您的问题,首先您需要确保运行您的代码的所有计算机都具有相同的定义,一旦您需要添加不属于该代码的其他字符,您就会遇到相同的问题选择的代码页。

因此,我建议您创建一个模拟 VBA 输入框的简单用户窗体。放置在用户窗体上的文本框可以处理您需要的所有字符。以下示例使用名为

frmInputBox
的表单,其中包含一个标签 (lblPrompt)、一个文本框 (tbInput) 以及 2 个用于确定和取消的按钮。

背后的代码很简单。

Option Explicit

Private returnValue As String

Public Function InputBox(Prompt As String, Optional title As String = "Input", Optional defaultValue As String = "")
    Me.lblPrompt = Prompt
    Me.Caption = title
    Me.tbInput = defaultValue
    returnValue = ""
    Me.Show
    InputBox = returnValue
End Function

Private Sub btnCancel_Click()
    returnValue = ""
    Me.Hide
End Sub

Private Sub btnOK_Click()
    returnValue = Me.tbInput.Value
    Me.Hide
End Sub

您现在要做的就是更改例程的代码以使用表单而不是 VBA

 With New frmInputBox
    engravingL1 = .InputBox("First line : ", "Write")
    Selection.TypeText Text:=engravingL1
    Selection.TypeParagraph
    
    engravingL2 = .InputBox("Second line: ", "Write")
    Selection.TypeText Text:=engravingL2
        
    fontName = .InputBox("Font name : ", "Write", "Arial")
    If fontName <> "" Then
        Selection.WholeStory
        Selection.Font.Name = fontName
        Selection.Font.Size = 11
    End If
End With
© www.soinside.com 2019 - 2024. All rights reserved.