尝试自动分割数据在Excel中与VBA

我绝对没有经验的编程在Excel VBA以外,我写了一个function,添加一个数据标签,在我们的生产线几个星期后,主要是通过试验和错误扫描的条形码。

无论如何,我现在需要的帮助是库存即将到来,我们每个项目都有一个条形码,通常扫描到记事本,然后手动拉入Excel和“文本到列”使用。 我发现了Excel的分割function,并希望能够帮助我的扫描条形码。

数据格式为:11111 * A153333 * 11/30/11加一个回车符,其中*为分隔符。 我发现的所有例子似乎都没有做任何事情。

例如,这里是我在“”分裂中find的一个,但如果将其更改为*,则不会发生任何反应。

Sub splitText() 'splits Text active cell using * char as separator Dim splitVals As Variant Dim totalVals As Long splitVals = Split(ActiveCell.Value, "*") totalVals = UBound(splitVals) Range(Cells(ActiveCell.Row, ActiveCell.Column + 1), Cells(ActiveCell.Row, ActiveCell.Column + 1 + totalVals)).Value = splitVals End Sub 

这在Sheet1代码部分应用,如果有帮助的话。

这真的不可能是这个复杂的,可以吗?

编辑:试图添加到VBA的Vlookup。

所以正如我在下面的评论中所说,我现在正在努力让vlookup集成到这个中,但是它只是返回N / A。

这里是我写的基于下面的链接

 Public Sub vlook(ByRef codeCell As Range) Dim result As String Dim source As Worksheet Dim destination As Worksheet Set destination = ActiveWorkbook.Sheets("Inventory") Set source = ActiveWorkbook.Sheets("Descriptions") result = [Vlookup(destination!(codeCell.Row, D), source!A2:B1397, 2, FALSE)] End Sub 

我试图在工作表中的For循环改变之后立即调用它,并且刚刚创build了另一个for循环,请问这是否应该是一个嵌套for循环?

只要将代码添加到工作表后面的VBA中,实际上并不会导致它被调用。 您需要处理worksheet_change事件。 以下应该有所帮助:

 Private Sub Worksheet_Change(ByVal Target As Range) Application.EnableEvents = False Dim cell As Range For Each cell In Target.Cells If cell.Column = 1 Then SplitText cell Next Application.EnableEvents = True End Sub Public Sub SplitText(ByRef codeCell As Range) 'splits Text active cell using * char as separator Dim splitVals As Variant Dim totalVals As Long splitVals = Split(codeCell.Value, "*") totalVals = UBound(splitVals) Range(Cells(codeCell.Row, codeCell.Column), Cells(codeCell.Row, codeCell.Column + totalVals)).Value = splitVals End Sub 

如果你想在输入条形码时自动处理条形码,你需要这样的东西(进入工作表模块)。

 Private Sub Worksheet_Change(ByVal Target As Range) Dim splitVals As Variant Dim c As Range, val As String For Each c In Target.Cells If c.Column = 1 Then 'optional: only process barcodes if in ColA val = Trim(c.Value) If InStr(val, "*") > 0 Then splitVals = Split(val, "*") c.Offset(0, 1).Resize( _ 1, (UBound(splitVals) - LBound(splitVals)) + 1 _ ).Value = splitVals End If End If 'in ColA Next c End Sub