Excel和VBA给出了不同的答案

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

我在数据验证时遇到了一个奇怪的问题(可能是一个错误)

当我使用下面的代码进行数据验证时,Excel创建了一个下拉菜单,但只添加了一行字符串,但当我从Excel数据验证菜单中写入相同的字符串时,Excel却用多个我想要的项目来分隔下拉菜单。但当我从Excel数据验证菜单中写下相同的字符串时,Excel却用我想要的多个项目来分隔下拉菜单。例如,让我们说字符串是 "A;B;C",当我用VBA做时,下拉菜单显示 "A;B;C "为一行,但当我点击数据验证菜单并手动写下 "A;B;C "时,Excel却用 "A"、"B"、"C "创建了3行下拉菜单,这是完全奇怪的行为。你可以看到下面的代码。我添加了视频链接以更好地解释。https:/streamable.coma75kud

Public arrAddress As String
Sub DynamicDataVal()

Dim rng As Range
Dim cll As Range
Dim dValicationCount As Long
Dim un As String
Dim DValidationList As Range
Dim DValidationListString As String
Dim seper As String
Dim col As New Collection, a
Dim colIt As Variant
Dim arr() As Variant

un = "Sayin " & Environ("UserName")

On Error Resume Next
Set rng = Application.InputBox("Lutfen Veri Alanini Seciniz", un, ActiveCell.Address, , , , , 8)
If rng Is Nothing Then Exit Sub

Set cll = ActiveCell
dValicationCount = cll.SpecialCells(xlCellTypeSameValidation).Count

If dValicationCount = 0 Then
    arr = rng.Offset(1, 0).Resize(rng.Resize(, 1).Cells.Count - 1, 1).Value
    arrAddress = rng.Address(External:=True)
    For Each a In arr
       col.Add a, a
    Next a
    seper = ListSeperatorMod.GetListSeparator
    For Each colIt In col
         DValidationListString = DValidationListString & seper & colIt
    Next colIt
    DValidationListString = Right(DValidationListString, Len(DValidationListString) - 1)
    On Error GoTo 0
    With cll.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:=DValidationListString
    End With
Else
    If rng.Validation.Type <> 3 Then
        Exit Sub
    Else
        'Will be done
    End If
End If
On Error GoTo 0
End Sub
Private Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" _
    (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long

Private Declare Function GetUserDefaultLCID% Lib "kernel32" ()
Private Const LOCALE_SLIST = &HC

Public Function GetListSeparator() As String

    Dim ListSeparator As String
    Dim iRetVal1 As Long
    Dim iRetVal2 As Long
    Dim lpLCDataVar As String

    Dim Position As Integer
    Dim Locale As Long

    Locale = GetUserDefaultLCID()

    iRetVal1 = GetLocaleInfo(Locale, LOCALE_SLIST, lpLCDataVar, 0)

    ListSeparator = String$(iRetVal1, 0)

    iRetVal2 = GetLocaleInfo(Locale, LOCALE_SLIST, ListSeparator, iRetVal1)

    Position = InStr(ListSeparator, Chr$(0))
    If Position > 0 Then
        ListSeparator = Left$(ListSeparator, Position - 1)
    End If

    GetListSeparator = ListSeparator

End Function
excel vba macros
1个回答
1
投票

这是由设计的,它是相同的行为,你会看到,如果使用VBA在单元格中输入公式:你总是使用 "美国 "列表分隔符。, 而不是(例如)本地特有的分隔符,如VBA中的 ;.

这与通过用户界面输入公式不同,在用户界面上,你总是使用特定的本地分隔符。

所以在VBA中,你可以使用:

Range("A1").Formula = "=MAX(A1, B2)"

如果你的locale分隔符是 ; 然后公式在工作表上显示为。

=MAX(A1; B2)

这样就可以让同一个VBA在不同的语言环境中运行而不需要修改

© www.soinside.com 2019 - 2024. All rights reserved.