我正在基于Excel的VBA中开发一个项目。在Excel中,有一个工作表,其中包含多列信息。通过使用下面的代码,我可以在单个列中搜索并在用户窗体中打印出其余数据。
第一个问题是:我要搜索的列(第1列)包含8个字符,但只需要搜索前6个字符。在任何情况下都可以吗?我尝试使用.Characters(1, 6)
,如下面的代码所示,但不起作用。
Sheet1包含大约5500行数据。
第二个问题是:我想在几个TextBox中打印出该行的数据,如下面的代码所示。 TextBox2应该在我的第一个问题(第1列)中包含搜索单元格的结果,但还是只包含前6个字符。我将如何完成?
我希望你能帮助我。
Public Sub Search_Owner()
Dim PrsNr As String
Dim Found As Range
PrsNr = TextBox1.value
Worksheets("Sheet1").Activate
Set Found = Worksheets("Sheet1").Range("A2", Range("A" & Rows.Count).End(xlUp)).Characters(1, 6).Find(PrsNr, Lookat:=xlWhole)
If Found Is Nothing Then
MsgBox "Nothing found", vbCritical
Else
TextBox2 = Cells(Found.Row, 1).value
TextBox3 = Cells(Found.Row, 5).value
TextBox4 = Cells(Found.Row, 8).value
End If
End Sub
"*"
方法中使用.Find
通配符。Left()
功能。这是方法:
Public Sub Search_Owner()
Dim PrsNr As String
Dim Found As Range
PrsNr = TextBox1.Value
Set Found = Worksheets("Sheet1").Range("A2", Range("A" & Rows.Count).End(xlUp)).Find(PrsNr & "*", Lookat:=xlWhole)
If Found Is Nothing Then
MsgBox "Nothing found", vbCritical
Else
TextBox2 = Left$(Cells(Found.Row, 1).Value, 6)
TextBox3 = Left$(Cells(Found.Row, 5).Value, 6)
TextBox4 = Left$(Cells(Found.Row, 8).Value, 6)
End If
End Sub