Excel - Unicode命名的单元格范围

时间:2017-12-05 21:21:19

标签: excel vba unicode

我写了一个小函数来加速命名单元格:

Public Sub InputSelectedNames()
    For Each Cell In Selection
        On Error Resume Next
        Dim strName As String
        strName = InputBox("Enter name for cell " & Cell.Address(False, False) & ":", "Name cell")
        If Len(strName) = 0 Then
            Exit Sub
        End If
        ActiveSheet.Names.Add Name:=strName, RefersTo:=Cell
    Next Cell
End Sub

这很有用,直到我尝试输入一个unicode字符串作为名称。如果我输入类似“αβγ”的东西,它会显示为“aß?”在InputBox中。

我读过关于VBA using ANSI encoding的信息,所以我理解为什么会这样。该教程中给出的示例解决方案适用于显示unicode(通过传递指针而不是字符串对象),但我无法对InputBox使用相同的想法。

如果我通过Excel的公式选项卡上的'定义名称'按钮输入这些字符,或者通过引用另一个单元格中的字符,它可以正常工作,所以误译似乎肯定存在于InputBox中。

我的猜测是我必须制作一个Userform来处理输入,除非有人知道让InputBox与unicode很好地配合的方法吗?

1 个答案:

答案 0 :(得分:0)

创建自定义InputBox确实解决了此问题。

Form layout

frmInputBox : UserForm
lblOutput : Label providing prompt
txtInput : TextBox for input
cmdOK : CommandButton for accepting input
cmdCancel : CommandButton for aborting prompt

VBA表单代码:

Private Sub cmdOK_Click()
    Accept
End Sub

Private Sub cmdCancel_Click()
    Cancel
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    Cancel
End Sub

Private Sub txtInput_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = vbKeyReturn Then
        Accept
    ElseIf KeyCode = vbKeyEscape Then
        Cancel
    End If
End Sub

Private Sub Accept()
    Me.Hide
End Sub

Private Sub Cancel()
    txtInput.Text = ""
    Me.Hide
End Sub

Public Function Prompt(strPrompt As String, Optional strTitle As String = "Input", Optional strDefault As String = "")
    With Me
        .Caption = strTitle
        .lblOutput.Caption = strPrompt
        .txtInput.Text = strDefault
        .StartUpPosition = 0
        .Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
        .Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
        .Show
    End With

    If txtInput.Text <> "" Then
        Prompt = txtInput.Text
    Else
        Prompt = ""
    End If
    Unload Me
End Function

称呼为:

strMyName = frmInputBox.Prompt("What's your name?", "Name Prompt")