我在Excel Visual Basic中为userform创建了一个函数,它改变了为一列选择的X的特定单元格值。但是,每次用户更改创建的用户表单中的值时,程序会将与该列相关的每个单元格中的数据与X值相乘。示例:如果我在列“A”中有值Marie三次,第三行,第7行和第10行中的一行以及我对“B”列的用户表单输入是hello。每行的输出将是相同的“hello”。但我想独立修改每个值,重复值“A”。
用户形式的代码:
Private Sub btnSubmit_Click()
Dim erow As Long
Dim ws As Worksheet
Dim lastrow As Long
Dim count As Integer
Set ws = ThisWorkbook.Sheets("Table")
lastrow = Sheets("Table").Cells(Rows.count, 1).End(xlUp).Row
count = 0
For x = 2 To lastrow
If Sheets("Table").Cells(x, 1) = Me.cmbEmp Then
ws.Cells(x, 3) = Me.ldlcolor
ws.Cells(x, 30) = (Me.ldlp)
count = count + 1
End If
If Sheets("Table").Cells(x, 3) = Me.cmbEmp Then
ws.Cells(x, 1) = Me.ldlname
ws.Cells(x, 14) = (Me.ldlI)
count = count + 1
End If
Next x
Me.Hide
End Sub
答案 0 :(得分:0)
问题是您循环遍历工作表的每一行,如果某个值在不同的行上重复,则每次都会匹配。您需要提供一种更好的方法来确定要修改的重复值。例如,此代码将循环直到找到第一次出现的数据(“marie”):
Dim bolFound As Boolean
bolFound = False
While Not bolFound
If Sheets("Table").Cells(x, 1) = Me.cmbEmp Then
ws.Cells(x, 3) = Me.ldlcolor
ws.Cells(x, 30) = (Me.ldlp)
count = count + 1
bolFound = True
End If
If Sheets("Table").Cells(x, 3) = Me.cmbEmp Then
ws.Cells(x, 1) = Me.ldlname
ws.Cells(x, 14) = (Me.ldlI)
count = count + 1
bolFound = True
End If
Wend
如果您不知道要更改哪个“marie”,那么您要么必须删除重复数据,要么想办法区分第3行的“marie”和第7行的marie。