0

我想将数据插入到 Excel 工作簿 1 并将其复制到工作簿 2。我需要确保新插入的数据不会在两个工作簿中重复。我使用C列中的文章编号(类型字符串)来检查数据是否已经在两个工作簿中,如果数据已经存在,用户需要重新输入。

我不知道如何使用哪个字符串函数来搜索字符串。这是我的一些代码(此代码仅用于在 workbook1 中输入新数据然后复制到 workbook2)。我用于检查的字符串在列 C(textbox1)

Workbooks("workbook1.xlsm").Activate
With Worksheets("sheet1")
    '~insert data
    .Range("B" & (i + CountProd)) = ComboBox1.Text
    .Range("C" & (i + CountProd)) = TextBox1.Text
    .Range("D" & (i + CountProd)) = TextBox2.Text
    .Range("E" & (i + CountProd)) = TextBox3.Text
    .Range("F" & (i + CountProd)) = TextBox4.Text
    .Range("G" & (i + CountProd)) = TextBox5.Text
    .Range("H" & (i + CountProd)) = ComboBox2.Text
    .Range("I" & (i + CountProd)) = TextBox6.Text
    .Range("J" & (i + CountProd)) = TextBox7.Text
    .Range("K" & (i + CountProd)) = TextBox8.Text

End With

Workbooks("workbook2.xlsm").Activate

RowNo = Workbooks(prod & " Input.xlsm").Worksheets("Input").Cells(31, 3).Value
RowNo = RowNo + 32

Set sh1 = Workbooks("workbook2.xlsm").Worksheets("sheet1")
Set sh2 = Workbooks("workbook1.xlsm").Worksheets("sheet1")

sh1.Range(sh1.Cells(RowNo, 2), sh1.Cells(RowNo, 11)).Value = sh2.Range(sh2.Cells((i + CountProd), 2), sh2.Cells((i + CountProd), 11)).Value
'        End If
4

2 回答 2

0

我想您需要的是一个函数,告诉您某个值是否存在于某个范围内。这是一段通用代码,可用于检查 [Arg] 是否包含在范围 [SRng] 的 [SCol] 列中的任何位置

Function Exist(Arg As String, SRng As Range, SCol As Long) As Boolean
Dim Idx As Long

    Idx = 1
    Exist = False

    Do While SRng(Idx, SCol) <> ""
        If SRng(Idx, SCol) = Arg Then
            Exist = True
            Exit Do
        End If
        Idx = Idx + 1
    Loop

End Function

使用此功能,您可以在任何地方检查是否存在货号……例如:

Sub Test()
' properly Dim your variables and objects
Dim Rng1 As Range, Rng2 As Range

    ' set ranges first - you don't need to "activate" sheets unless you
    ' want the display to hop around
    ' avoid hardcoding as much as possible
    Set Rng1 = Workbooks("workbook1.xlsm").Worksheets("sheet1").[A1]
    Set Rng2 = Workbooks("workbook2.xlsm").Worksheets("sheet1").[A1]

    ' then start logic
    If Exist(TextBox1.Text, Rng1, 3) Then
        ' ANr exists somewhere in book1/sheet1/[C..C]
    Else
        ' ANr does not exist in book1/sheet1/[C..C]
    End If

    If Exist(TextBox1.Text, Rng2, 2) Then
        ' ANr exists somewhere in book2/sheet1/[B..B]
    Else
        ' ANr does not exist in book2/sheet1/[B..B]
    End If


End Sub
于 2013-03-04T07:54:08.080 回答
0

要检查 textbox1 中的字符串是否已存在于 C 列中,您可以使用“查找”功能:

on error resume next
lRow = range("C:C").find(textbox1.text,...).row

if err.number = 0 then    'string found
   msgbox "Duplicate value. Try again."
   exit sub
end if

on error goto 0
于 2013-03-04T16:16:14.730 回答