VBA非常新,我需要一些听起来很简单的东西,但我缺乏正确研究如何做到这一点的知识或术语。
我需要一种方法来遍历一个列(我们说D)来找到值(X)并从范围(T2:T160)中提示一个下拉框来替换X中每个单独出现的值X.行1到10000。
对于每次找到X,同样需要显示列B的该行中的值(用户将查询外部应用程序以确定需要为该唯一列设置该范围中的哪些值B值)
1 b
2 y
3 x
4 t
5 x
并以此结束
1 b
2 y
3 q
4 t
5 p
答案 0 :(得分:2)
我设置了这样的数据:
主要代码:
Sub findReplace()
Dim iReply As Integer
Dim strName As String
strName = InputBox(Prompt:="Enter Text to Search in Column D", Title:="Search Text", Default:="Enter value to find")
If strName = "Enter value to find" Or strName = vbNullString Then
Exit Sub
Else
For Each cell In Range("D1:D5")
If cell.Value = Trim(strName) Then
'Prompt to see if new value is required
iReply = MsgBox(Prompt:="Found " & strName & vbCrLf & "Value in column B is: " & cell.Offset(0, -2).Value & vbCrLf & "Do you wish to replace it?", _
Buttons:=vbYesNoCancel, Title:="UPDATE MACRO")
'Test response
If strName = "Your Name here" Or _
strName = vbNullString Then
Exit Sub
ElseIf iReply = vbYes Then
'Get new value
UserForm1.Show
ValueSelected = UserForm1.ComboBox1.Value
Unload UserForm1
If ValueSelected = vbNullString Or ValueSelected = "" Then
Exit Sub
Else
'Replace value
cell.Value = ValueSelected
End If
ElseIf iReplay = vbCancel Then
Exit Sub
End If
End If
Next cell
End If
End Sub
设置UserForm1以显示下拉列表,为用户提供选择选项。表单背后的代码如下所示:(按钮必须命名相同才能正常工作)
Private Sub bnt_Cancel_Click()
Unload Me
End Sub
Private Sub btn_Okay_Click()
Me.Hide
End Sub
Private Sub UserForm_Initialize()
'Populate dropdown list in userform
Dim rng As Range
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
For Each rng In ws.Range("T1:T10")
Me.ComboBox1.AddItem rng.Value
Next rng
End Sub
当你运行它时,你会得到这一系列的弹出窗口:
我对第二个替换值说不,所以现在我的电子表格看起来像这样: