我是一名vba初学者,正在为一家小公司构建CRM电子表格。我有一个公司/客户名称的工作表,我试图从另一个工作表中提取他们的联系信息,并在弹出的用户表单中显示它。
我的用户表单列出了与文本框的单独联系信息,因此我使用.Find / FindNext函数填充它们。但是FindNext会一直回到开头,导致userform再次显示相同的名称。
如何在不使用循环的情况下阻止.FindNext包装?
我已经尝试将它放在一个Do-Loop中,但这似乎把它放在一个无限循环或其他东西并冻结excel。我也试过没有运气的LastRow公式。
Sub UserForm_Activate()
Dim fSearch As Range 'the column we are searching in
Dim fFind As Range 'the value we are searching for
Dim LastRow As Long
Set fSearch = Sheets("Contact List").Range("Company_Find")
'First Find
Set fFind = fSearch.Find(What:=Selection.Value)
Debug.Print
Txt_Contact1 = fFind.Offset(0, 5)
Txt_Title1 = fFind.Offset(0, -1)
Txt_Email1 = fFind.Offset(0, 1)
Txt_Office1 = fFind.Offset(0, 2)
Txt_Mobile1 = fFind.Offset(0, 3)
'Second Find
Set fFind = fSearch.FindNext(fFind)
Debug.Print
Txt_Contact2 = fFind.Offset(0, 5)
Txt_Title2 = fFind.Offset(0, -1)
Txt_Email2 = fFind.Offset(0, 1)
Txt_Office2 = fFind.Offset(0, 2)
Txt_Mobile2 = fFind.Offset(0, 3)
'Third Find
Set fFind = fSearch.FindNext(fFind)
Debug.Print
Txt_Contact3 = fFind.Offset(0, 5)
Txt_Title3 = fFind.Offset(0, -1)
Txt_Email3 = fFind.Offset(0, 1)
Txt_Office3 = fFind.Offset(0, 2)
Txt_Mobile3 = fFind.Offset(0, 3)
'Fourth Find
'Fifth Find
End Sub
Set fFind = fSearch.Find(What:=Selection.Value)
If Not fFind Is Nothing Then
'Save the address of the first found range to compare with later
Fadd = fFind.Address
End If
Do While Not fFind Is Nothing
'Do stuff
Set fFind = fSearch.FindNext(fFind)
If Not fFind is Nothing Then
'If the next found address is the same as the first, stop searching, exit the loop
If fFind.Address = Fadd Then Exit Do
End If
Loop
这是我的方法。希望能帮助到你。我估计你没有正确退出你的Do...Loop
,因此杀死Excel的无限循环。除非您更改第一个找到的范围的值,否则此循环将退出。
使用循环然后为每次必须搜索时编写Find方法要好得多。这导致硬编码发现“循环”,在迭代中没有灵活性。
编辑
下面的代码将循环填充UF
中的所有文本框,并在所有文本框都填满后退出循环/没有找到新值
Dim ctrl as Control
Dim b as Integer
Set fFind = fSearch.Find(What:=Selection.Value)
If Not fFind Is Nothing Then
b = 1
'Save the address of the first found range to compare with later
Fadd = fFind.Address
End If
Do While Not fFind Is Nothing
For Each ctrl In Me.Controls
If ctrl.Name Like "Txt_Contact" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 5)
If ctrl.Name Like "Txt_Title" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, -1)
If ctrl.Name Like "Txt_Email" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 1)
If ctrl.Name Like "Txt_Office" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 2)
If ctrl.Name Like "Txt_Mobile" & b And ctrl.Value = "" Then ctrl.Value = fFind.Offset(0, 3)
Next ctrl
Set fFind = fSearch.FindNext(fFind)
If Not fFind is Nothing Then
'If the next found address is the same as the first, stop searching, exit the loop
If fFind.Address = Fadd Then Exit Do
End If
b = b + 1
Loop