我有一个UserForm用于输入翻译。标题文本框(txtTitle),要翻译的文本(txtToTranslate)和翻译文本(txtTranslation)以及用于选择语言的文字框(cboLanguage)。
每次用户点击提交时,代码都会创建一个新的数据行。 我想修改功能如下:
1单击“提交”,检查A:A
中是否已存在txtTitle2a如果txtTitle不存在,请创建新行(当前功能)
2b如果存在txtTitle,请将txtTranslation添加到包含txtTitle的行,而不是“NextRow”
Private Sub btnSubmit_Click()
Dim FindString As String
Dim Rng As Range
FindString = "*" & txtTitle
If Trim(FindString) & "*" <> "" Then
With Sheets("output").Range("A:A")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
????
Else
Sheets("output").Activate
NextRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1
Cells(NextRow, 1) = txtTitle.Text
Cells(NextRow, 2) = txtToTranslate.Text
If cboLanguage = "fr-FR" Then Cells(NextRow, 3) = txtTranslation.Text
If cboLanguage = "it-IT" Then Cells(NextRow, 4) = txtTranslation.Text
If cboLanguage = "de-DE" Then Cells(NextRow, 5) = txtTranslation.Text
Unload frmNewTranslation
End If
End With
End If
End Sub
答案 0 :(得分:1)
以下是我的意思:
Dim rng as Range
Dim FindString as string
FindString = "*" & Trim(txtTitle) & "*" 'this will match any occurance of txtTitle in a target cell
Set rng = Range("A1") 'set starting range cell
While rng.value <> ""
If rng.Value Like FindString
'your code to update the current row here
Exit Sub
End If
Set rng = rng.Offset(1, 0) 'offset the cell down one
Wend
'your code to create the new row here. rng will be positioned at the next empty cell
这有帮助吗?对正在发生的事情的简短解释(为了帮助您一路走来):
首先,我们将范围变量设置为我们要搜索的最顶层单元格(在本例中为A1)。然后我们输入一个循环:如果检查rng
的值是否与FindString
匹配,如果是,则可以将代码放在那里,以便在找到匹配时执行任何操作。 如果在该行中找不到匹配项,则If
块不会执行,rng
将设置为其下方的单元格(将我们放下一个),然后循环重复。循环将一直运行,直到找到第一个空白单元格,因此它假定列中没有空格。在找到空白单元格的时刻,循环结束并且代码继续。但是,rng
设置为空白单元格,因此您可以创建一个新行:
rng.value = 'whatever
rng.offset(0, 1).value = 'next column whatever
rng.offset(0, 2).value = 'third column whatever
等等。