另一个工作表中有一个单元格,其值的范围是1到100,我在名称管理器中将其名称定义为“ SpanLength”。在我现在关心的工作表中,我想找到包含与“ SpanLength”相同的值,即从1到100的值,在我定义为“ FindSpanLength”的范围内的单元格。然后,我想调用此单元格在“ outputcolumn”内的列,以便可以在脚本中进一步使用此列。我该怎么办?
End Sub之前的代码行导致错误消息“参数数量错误或属性分配无效”
我是VBA的新手,毫无疑问我的代码充满错误,因此,我将不胜感激。我已经在google上搜索了答案,但是还没有找到足够具体的信息让我理解。
Sub OutputMaximums()
Dim spanlengthcell As Range
Set spanlengthcell = Range("FindSpanLength").Find("SpanLength")
Range("spanlengthcell").Column(1) = outputcolumn
End Sub
新代码,出现错误消息1004(对象“ _Worksheet”的方法“范围”失败):
Sub OutputMaximums()
Dim spanlengthcell As Range, outputcolumn As Long
Set spanlengthcell = OUTPUT.Range("FindSpanLength").Find(Range("SpanLength").Value)
If Not spanlengthcell Is Nothing Then
outputcolumn = spanlengthcell.Column
End If
End Sub
答案 0 :(得分:0)
Sub ShowNamedRange()
'The named Range "SpanLenght" must be on the Sheet "SheetWithNamedRange"!
Debug.Print Sheet("SheetWithNamedRange").Range("SpanLength").Address
Debug.Print Sheet("SheetWithNamedRange").Range("SpanLength").Column
End Sub
然后再次阅读问题:
Sub SearchRange()
Dim rngSearch As Range
Dim rngFound As Range
Dim strSearch As String
strSearch = Sheets("SheetWithNamedRange").Range("SpanLength").Value
Set rngSearch = Sheets("SheetWithFINDRange").Range("FindSpanLength")
Set rngFound = rngSearch.Find(strSearch)
If Not (rngFound Is Nothing) Then _
MsgBox "Found in column " & rngFound.Column & _
" on the sheet """ & rngFound.Parent.Name & """!"
End Sub
答案 1 :(得分:0)
为变量分配值时,该变量位于等号的左侧。
使用Find
时,请始终先检查是否找到了搜索词,然后再尝试访问其属性,以避免后续错误。
还建议指定许多Find
参数,因为它们自上次在工作表上使用以来可能具有意外的设置。
Sub OutputMaximums()
Dim spanlengthcell As Range, outputcolumn As Long
Set spanlengthcell = Range("FindSpanLength").Find(Range("SpanLength").Value)
If Not spanlengthcell Is Nothing Then
outputcolumn = spanlengthcell.Column
End If
End Sub
答案 2 :(得分:0)
Option Explicit
Sub test()
Dim rngSearch As Range, rngFound As Range
Dim strSearch As String
Dim ColumnNo As Long
strSearch = "Bingo"
With ThisWorkbook.Worksheets("Sheet1")
Set rngSearch = .UsedRange
Set rngFound = rngSearch.Find(strSearch)
If rngFound Is Nothing Then
MsgBox strSearch & " does not excist in range."
Else
ColumnNo = rngFound.Column
MsgBox "Text appears in column " & ColumnNo & "."
End If
End With
End Sub