簡體   English   中英

電子表格中的問號導致Excel VBA中的問題

[英]Question mark in spreadsheet causes problems in Excel VBA

當我比較包含?的單元格的值時 到變量,它總是返回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?

據我了解,您想創建一個替換算法。 如果沒有特定的原因使用二維密碼表,我寧願使用一維方法,如下所示:

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+-再次得到THEQUICKBROWN(?)FOX123+- ,這與對稱替換所期望的一樣。

我嘗試了以下操作,並獲得了預期的結果(它能夠找到問號):

(1)如上在工作表中創建CipherTable范圍;

(2)創建了與上述代碼相似的功能QM;

(3)輸入= QM(cell-ref)樣式的公式。

工作正常。 功能質量管理:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM