我想将数据插入excel workbook1并将其复制到workbook2。我需要确保新插入的数据不会在两个工作簿中重复。我在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
答案 0 :(得分: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
答案 1 :(得分: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