因此,我在两列中包含以下单词,而我想做的是创建一个输入框,在其中找到该单词并提取它以及行号。我曾经做过一次,但是现在它一直给我一个调试错误,我无法弄清。
任何帮助将不胜感激(理想情况下,无需更改很多代码:P)
The any
Quick of
Brown my
Fox lazy
jumps dogs
Over
Option Explicit
Option Base 1
Sub AddMessage()
Dim i As Integer, j As Integer, HT As Variant, nr As Integer, nc As Integer, c As Integer, rng1 As Range, rng2 As Range, row As Integer, rows As Integer
nr = Selection.rows.Count
nc = Selection.Columns.Count
HT = InputBox("Enter column letter:")
Set rng1 = Range("E1:E100")
Set rng2 = Range("F1:F100")
For i = 1 To nr
For j = 1 To nc
If ActiveCell(i, j) = HT Then
Selection.Cells(i, j - 4) = HT
If Cells(i, 1).Value = HT Then
row = Application.WorksheetFunction.match(HT, rng1, 0)
Selection.Cells(i, j - 2) = row
Else
If Cells(i, 2).Value = HT Then
rows = Application.WorksheetFunction.match(HT, rng2, 0)
Selection.Cells(i, j - 2) = row
End If
End If
Next j
Next i
End Sub
答案 0 :(得分:0)
您错过了End If
适当的缩进会帮助您弄清楚:
Sub AddMessage()
Dim i As Integer, j As Integer, HT As Variant, nr As Integer, nc As Integer, c As Integer, rng1 As Range, rng2 As Range, row As Integer, rows As Integer
nr = Selection.rows.Count
nc = Selection.Columns.Count
HT = InputBox("Enter column letter:")
Set rng1 = Range("E1:E100")
Set rng2 = Range("F1:F100")
For i = 1 To nr
For j = 1 To nc
If ActiveCell(i, j) = HT Then
Selection.Cells(i, j - 4) = HT
If Cells(i, 1).Value = HT Then
row = Application.WorksheetFunction.Match(HT, rng1, 0)
Selection.Cells(i, j - 2) = row
Else
If Cells(i, 2).Value = HT Then
rows = Application.WorksheetFunction.Match(HT, rng2, 0)
Selection.Cells(i, j - 2) = row
End If '<<<=== missing End If
End If
End If
Next j
Next i
End Sub
答案 1 :(得分:0)
不知道您是否需要选择(我建议不要),这是另一段没有'activecells'和'selections'的代码
Sub tst()
Dim HT As String, Rng As Range
HT = InputBox("Give word to find:")
If Trim(HT) <> "" Then
With Sheets("Sheet1").Range("E1:F100")'assume your data is on Sheet1
Set Rng = .Find(What:=HT, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not Rng Is Nothing Then
Sheets("Sheet1").Cells(Rng.Row, 2) = Rng.Value: Sheets("Sheet1").Cells(Rng.Row, 4) = Rng.Row
Else
MsgBox "No words found"
End If
End With
End If
End Sub