【问题标题】:Highlighting word excel突出显示词excel
【发布时间】:2015-06-23 17:32:31
【问题描述】:

我正在编写一个 VBA 程序,它允许我通过一组 Excel 数据进行挖掘并提取相关信息,然后将这些信息复制到另一个工作表中。

我一直在尝试使正在搜索的单词以黄色突出显示,但是我的程序不断抛出“编译错误 - Ubound 上的预期数组”。

Option Compare Text

Public Sub Textchecker()
'
' Textchecker
'
' Keyboard Shortcut: Ctrl+h
'
Dim Continue As Long
Dim findWhat As String
Dim LastLine As Long
Dim toCopy As Boolean
Dim cell As Range
Dim item As Long
Dim j As Long
Dim sheetIndex As Long
Dim inclusion As String

sheetIndex = 2

Continue = vbYes
    Do While Continue = vbYes

        findWhat = CStr(InputBox("What word would you like to search for today?"))
        inclusion = CStr(InputBox("Do you have any inclusions? Separate words with commas"))
        LastLine = ActiveSheet.UsedRange.Rows.Count
        If findWhat = "" Then Exit Sub
        j = 1
    For item = 1 To LastLine
        If UBound(inclusion) >= 0 Then
            For Each cell In Range("BY1").Offset(item - 1, 0) Then
                For Each item In inclusion
                    If InStr(cell.Text, findWhat) <> 0 And InStr(cell.Text, inclusion) <> 0 Then
                        findWhat.Interior.Color = 6
                        toCopy = True
        Else
            For Each cell In Range("BY1").Offset(item - 1, 0) Then
                If InStr(cell.Text, findWhat) <> 0 Then
                    findWhat.Interior.Color = 6
                    toCopy = True
            End If
        Next item
        End If
        Next
        If toCopy = True Then
            Sheets(sheetIndex).Name = UCase(findWhat) + "+" + LCase(inclusion)
            Rows(item).Copy Destination:=Sheets(sheetIndex).Rows(j)
            j = j + 1
        End If
        toCopy = False
    Next item
    sheetIndex = sheetIndex + 1
    Continue = MsgBox(((j - 1) & " results were copied, do you have more keywords to enter?"), vbYesNo + vbQuestion)
Loop
End Sub

我在这里做错了什么?

【问题讨论】:

  • 它在哪里抛出错误?顺便说一句,我相信您的代码没有正确粘贴在中间。你有一个 Next 和 End If 在同一行。
  • 是的,它没有正确粘贴。我更新显示了一个错误,但我得到了多个。我继续尝试粘贴它。

标签: vba excel


【解决方案1】:

在您的代码中,inclusion 被声明为String 变量,并包含String,尽管String 以逗号分隔。 Ubound 函数适用于数组。

解决方法:使用Split 函数将字符串转换为数组。请参阅以下示例以获得一些快速帮助,如果您需要更多详细信息,请告诉我们。

Sub Tests()
    Dim inclusion() As String

    inclusion = Split("One, Two, Three", ",")

    MsgBox (UBound(inclusion))
End Sub

【讨论】:

  • 谢谢!感谢您的帮助,我的程序现在抛出错误“编译错误 - 对于数组上的每个控件必须是 Variant”
  • @wesree 我想说部分问题可能在于您在嵌套循环中的两个单独实例中使用item 变量。您使用For item = 1...For Each item in Inclusion...
【解决方案2】:

回答您最后的评论。

For Each 中的变量必须是 Object 或 Variant 类型。

要更改 Variant 中的“item”,请将“Dim item As Long”替换为“Dim item As Variant”,甚至替换为“Dim item”,因为声明的变量没有类型是 Variant。

【讨论】:

    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 2014-08-07
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多