搜索值 x 的列并将用户表单数据复制到适用行

Search column for value x and copy userform data to applicable row

我得到了下面的代码,我将 k 指定为文本框值以检查它是否正常工作(似乎是)但它仍然拒绝搜索列 A 并只是执行 Else 参数。

    Private Sub CommandButton1_Click()

Dim FoundCell As Range
Set FoundCell = Sheets("WATCH LOG").Range("A:A").Find(What:=WN.Value)
    k = FoundCell.Value

If k = WN.Value Then
        j = FoundCell.Row
            Sheets("WATCH LOG").Cells(j, 6).Value = Me.DMN.Value
            Sheets("WATCH LOG").Cells(j, 7).Value = Me.DWN.Value
            Sheets("WATCH LOG").Cells(j, 8).Value = Me.DOE.Value
End If
    Else
    MsgBox "WATCH NOT FOUND"

End Sub

根据评论添加注释:

WNDMNDWNDOE 是用户表单文本字段。

试试这个

Private Sub CommandButton1_Click()

Dim FoundCell As Range
Set FoundCell = Sheets("WATCH LOG").Range("A:A").Find(What:=WN) 'Take away the .Value within the Find
    k = FoundCell.Value

If k = WN.Value Then
        j = FoundCell.Row
            Sheets("WATCH LOG").Cells(j, 6).Value = Me.DMN.Value
            Sheets("WATCH LOG").Cells(j, 7).Value = Me.DWN.Value
            Sheets("WATCH LOG").Cells(j, 8).Value = Me.DOE.Value
End If
    Else
    MsgBox "WATCH NOT FOUND"

End Sub

据我了解您的代码的用途,您想要查找在 A 列的第一个文本框 WN 中输入的搜索字符串,然后写入后续的文本框字符串 DMNDWNDOE 到找到的行内的给定偏移量。

对多个问题的一些提示:

  • 声明所有变量(使用 Option Explicit
  • 使用完全限定的范围引用
  • 提到工作表更喜欢 Worksheets 集合,因为 Sheets 也可能包括形状
  • 严格缩进代码以避免错误的 If .. Else ..EndIf 构造(顺便说一句,这会引发编译错误)
  • 为找不到搜索字符串的情况提供服务,例如通过 If Not FoundCell Is Nothing Then;这可以让你避免像 If k = WN.Value Then 这样的额外检查,因为如果你找到了搜索项,它是相同的

此外,我演示了一种方法,通过 Array(DMN, DWN, DOE) 通过一个代码行将所有后续文本框值写入到 A 列中找到的单元格的 +5 列的给定偏移量:)

Option Explicit                               ' declaration head of code module

Private Sub CommandButton1_Click()
' Purpose: find search string of 1st textbox and write subsequent strings to found row
With ThisWorkbook.Worksheets("WATCH LOG")     ' use fully qualified range reference
    Dim FoundCell As Range
    Set FoundCell = .Range("A:A").Find(What:=WN, LookAt:=xlWhole,  MatchCase:=False)

    If Not FoundCell Is Nothing Then          ' search string found
        FoundCell.Offset(0, 5).Resize(1, 3) = Array(DMN, DWN, DOE)
    Else                                      ' provide for non-results
        MsgBox "WATCH NOT FOUND"
    End If
End With

End Sub