Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 如何比较列中的字符串,然后在字符串不存在时复制数据';不匹配_Excel_Vba - Fatal编程技术网

Excel 如何比较列中的字符串,然后在字符串不存在时复制数据';不匹配

Excel 如何比较列中的字符串,然后在字符串不存在时复制数据';不匹配,excel,vba,Excel,Vba,我想将数据插入excel workbook1并复制到workbook2。我需要确保新插入的数据不会在两个工作簿中重复。我使用C列中的物品编号(类型字符串) 若要检查数据是否已在两个工作簿中,如果数据已存在,则用户需要重新输入 我不知道如何使用哪个字符串函数来搜索字符串。这是我的一些代码(此代码仅用于在workbook1中输入新数据,然后复制到workbook2)。我用于检查的字符串位于C列(textbox1) 我想你需要的是一个函数,告诉你某个值是否存在于某个范围内。下面是一段通用代码,可用于检

我想将数据插入excel workbook1并复制到workbook2。我需要确保新插入的数据不会在两个工作簿中重复。我使用C列中的物品编号(类型字符串) 若要检查数据是否已在两个工作簿中,如果数据已存在,则用户需要重新输入

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


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

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

要检查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

谢谢,但是函数返回初始值Exist=False,尽管workbook2中存在textbox1.value。变量Idx是行号对吗?请检查调用中的列号(第3个参数)。。。。我将其设置为2是为了演示这种方法的灵活性——并检查两个范围的左上角(此处[A1]),是的。。。Idx是相对于您的手伸范围左上角的行号。我已经尝试过lRow=Workbooks(“Workbook2.xlsm”)。Worksheets(“Sheet1”)。Range(“C:C”)。Find(“&ArtNo,C32,3)。Row但是仍然没有找到字符串,尽管字符串存在于Workbook2中。您研究过Range.Find方法的参数吗?
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
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