电子表格中的问号会导致Excel VBA出现问题

时间:2011-01-07 21:21:31

标签: excel-vba excel-2002 vba excel

当我将包含?的单元格的值与变量进行比较时,它总是返回true。有什么办法可以阻止这个吗?这是我目前的代码:

'Option Explicit
Dim hws As Worksheet
Set hws = ActiveSheet
Dim rng As Range, rng2 As Range
Dim letters(2, 2)
alpha = Range("CipherTable").Value

For x = 1 To 7
  For y = 1 To 7
    If alpha(x, y) = rng.Cells(i, j + 1).Value Then
      letters(2, 1) = x
      letters(2, 2) = y
    End If
  Next y
Next x
顺便说一下,

alpha看起来像这样:

A   B   C   D   E   F   G
H   I   J   K   L   M   N
O   P   Q   R   S   T   U
V   W   X   Y   Z   1   2
3   4   5   6   7   8   9
0   ;   :   '   "   .   ,
(   )   _   -   +   ?   !

这总是返回A,它是alpha(1,1)。来想一想,因为他们每个人都去了七,我不知道为什么它不回来!。我怎样才能解决这个问题,只有当它实际匹配时才能返回true?

2 个答案:

答案 0 :(得分:1)

据我了解,你想创建一个替代算法。如果没有特别的理由使用二维密码表,我宁愿使用如下的一维方法:

Function Cipher(Argument As String) As String
Dim Model As String
Dim Subst As String
Dim Idx As Integer
Dim MyPos As Integer

    Cipher = ""
    ' note double quotation mark within string
    Model = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890;:'"".,()_-+?!"
    Subst = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890;:'"".,()_-+?!"

    For Idx = 1 To Len(Argument)
        ' get position from Model
        MyPos = InStr(1, Model, UCase(Mid(Argument, Idx, 1)))
        ' return character from substitution pattern
        If MyPos <> 0 Then Cipher = Cipher & Mid(Subst, MyPos, 1)
    Next Idx

End Function

调用此函数
Sub Test()
    Debug.Print Cipher("The quick brown (?) fox 123 +-")
End Sub

结果为THEQUICKBROWN(?)FOX123+-(因为我们不允许ModelSubst中的空白

现在将Subst更改为

Subst = "!?+-_)(,.""':;0987654321ZYXWVUTSRQPONMLKJIHGFEDCBA"

结果为4,_73.+'?6910GBF)9ZWVUCD

如果您将上述内容提供给密码函数,则会以THEQUICKBROWN(?)FOX123+-的形式再次以对称替换的方式结束。

答案 1 :(得分:0)

我尝试了以下内容,并获得了预期的结果(它能够找到问号):

(1)在工作表中创建CipherTable范围,如上所述;

(2)创建了与上述代码类似的函数QM;

(3)以= QM(cell-ref)的样式输入公式。

工作得很好。功能QM:

Public Function QM(theChar)

    Dim CipherTable
    Dim x As Integer
    Dim y As Integer

    CipherTable = Range("CipherTable").Value

    For x = 1 To 7
        For y = 1 To 7
            If CipherTable(x, y) = theChar Then
                QM = "X" & x & "Y" & y
                Exit Function
            End If
        Next y
    Next x

    QM = ""

End Function

====

我也尝试了更直接的方法,并得到了预期的回应:

Public Sub QM2()

    Dim questMark As Range
    Dim someChar As String
    Set questMark = Range("CipherTable").Cells(7, 6)

    someChar = "A"
    Debug.Print questMark = someChar

End Sub