单元格长度为10个字符时自动打印Excel

我正在设置一个迷你程序,以便操作员扫描条形码,在Excel中创build一个条形码并将其打印在标签打印机上。

我需要它在自动扫描10位数码后自动打印。

我到目前为止是 –

选项显式

Private Sub Worksheet_Change(ByVal Target As Range) If Len(Sheet1!A2) = 10 Then ActiveWorkbook.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False Sheets("Sheet1").Range("A2").ClearContents End If End Sub 

这似乎并没有工作。 我在Sheet1中有这个代码。 我得到的错误信息是

运行时错误“438”对象不支持此属性或方法

它突出了If Len位作为问题。

任何人都可以帮忙吗?

一般来说,当你用扫描仪扫描一个条形码时,它会发送一个数字,并发送一个“input”符号或回车,所以我会用它作为触发器(Worksheet_SelectionChange),而不是在工作表上进行任何更改。

但无论错误如何,您没有正确引用单元格

 If Len(Sheet1!A2) = 10 Then 

应该

 if Len(Sheets("Sheet1").Range("A2").Value) = 10 Then 

如果你打算让它触发一个特定的单元格更改然后使用此代码:

  Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) 'Checks if A2 was the changed cell If Intersect(Target, Sheets("Sheet1").Range("A2")) Is Nothing Then Exit Sub Else Application.EnableEvents = False 'to prevent endless loop If Len(Target.Value) = 10 Then ActiveWorkbook.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False Target.ClearContents Else End If End If Application.EnableEvents = True End Sub 

从这里使用Peter的代码: excel VBA在单元格更改时自动运行macros