-1

我有一个用于输入翻译的用户表单。有用于标题 (txtTitle)、要翻译的文本 (txtToTranslate) 和已翻译文本 (txtTranslation) 的文本框以及用于选择语言的组合框 (cboLanguage)。

当前,每次用户单击提交时,代码都会创建一个新的数据行。我想修改功能如下:

1 点击提交,检查A:A中是否已经存在txtTitle

2a 如果 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
4

1 回答 1

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)。然后我们进入一个循环: if 检查是否rng匹配 the的值FindString,如果匹配,您可以将代码放在那里,以便在找到匹配项时执行任何需要执行的操作。如果在该行中没有找到匹配项,则If块不会执行,rng并被设置到它下面的单元格(将我们下拉一个),然后循环重复。循环将一直运行,直到找到第一个空白单元格,因此它假定列中没有空白。在找到空白单元格的那一刻,循环结束,代码继续。但是,rng设置为空白单元格,因此您可以像这样创建一个新行:

rng.value = 'whatever
rng.offset(0, 1).value = 'next column whatever
rng.offset(0, 2).value = 'third column whatever

等等。

于 2013-07-17T15:37:37.450 回答