VBA:无效的资格赛

时间:2017-06-01 13:28:16

标签: excel vba

我的vba代码应该组织一个资产负债表,我只是从PDF中粘贴Excel。因此,与大多数资产负债表一样,有项目的描述(资产/负债/等)以及正在分析的年份的值。

首先,我试图确定文本在哪个位置结束。所以我编写了以下代码,它给了我和错误(无效限定符)。

Dim subjectCell As String
Dim letters As String
Dim index As Integer

letters = "qwertyuiopasdfghjklçzxcvbnmQWERTYUIOPASDFGHJKLÇZXCVBNM "
subjectCell = ActiveCell.Value

For i = 0 To Len(subjectCell) - 1

    If (letters.Contains(Mid(subjectCell, i + 1, 1))) Then
    Else
     index = i
Next i

Cell("A1").Value = index

2 个答案:

答案 0 :(得分:0)

Sub test()
    Dim subjectCell As String
    Dim letters As String
    Dim index As Integer

    letters = "qwertyuiopasdfghjklçzxcvbnmQWERTYUIOPASDFGHJKLÇZXCVBNM "
    subjectCell = ActiveCell.Value2

    For i = 1 To Len(subjectCell)
        If InStr(1, letters, Mid(subjectCell, i, 1), vbTextCompare) = 0 Then
            index = i
            Exit For
        End If
    Next i
    Range("A1").Value2 = index
End Sub

答案 1 :(得分:0)

这里有一些问题

  1. 如果您的if语句
  2. ,则无止境
  3. 如果您要定义类似A1的范围,则单元格应为range,单元格为1,1类型参考
  4. 使用ActiveCell的形式很差,明确定义
  5. 使用Range("A1").Value更好但形式也很差,完全定义为workbooks("book1.xlsx").sheets("Sheet1").Range("A1").Value
  6. 您无法在vba中使用letters.function(类型,我已经说明instr(或在字符串中)来说明这可以起到类似的效果。
  7. 我已经更改了您的代码,以便更好地说明它应该是什么样子:

    Sub g()
        Dim subjectCell As String
        Dim letters As String
        Dim index As Integer
    
        letters = "qwertyuiopasdfghjklçzxcvbnmQWERTYUIOPASDFGHJKLÇZXCVBNM "
        'subjectCell = ActiveCell.Value
        subjectCell = "a"
        For i = 0 To Len(subjectCell) - 1
    
            If InStr(letters, subjectCell) > 0 Then
                Debug.Print "Found it!  It starts at position: " & InStr(letters, subjectCell)
            Else
                Debug.Print "No Match"
                index = i
            End If
        Next i
    
        Range("A1").Value = index
    End Sub