我正在编写一个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
我在这里做错了什么?
答案 0 :(得分:1)
在您的代码中,inclusion
被声明为String
变量,并且包含String
,尽管以逗号分隔的String
。 Ubound
函数适用于数组。
修复:使用Split
函数将字符串转换为数组。有关快速帮助,请参阅以下示例,如果您需要更多详细信息,请告知我们。
Sub Tests()
Dim inclusion() As String
inclusion = Split("One, Two, Three", ",")
MsgBox (UBound(inclusion))
End Sub
答案 1 :(得分:0)
回答你的上一条评论。
For Each中的变量必须是Object或Variant类型。
要更改Variant中的“item”,请将“Dim item As Long”替换为“Dim item As Variant”,或者将“Dim item”替换为声明为不带类型的变量。