在打印和更改值时填充零

时间:2019-05-08 20:57:13

标签: excel vba

我是新来的,但希望大家能为我正在努力的解决方案提供帮助。我正在处理一个Excel文档并设置一个宏。在我尝试添加一些逻辑以将数字填充为零之前,它一直有效。

我正在尝试在标签小于10的选择单元格中填充零,然后添加我的整数。如果标签大于9,则我希望将零填充零,同样,当标签大于99时,也要填充10或更多的零。

我的程序询问用户他们希望打印多少标签(1-999)。

我尝试在For I = 1 To LabelCount中添加IF语句:

    For I = 1 To LabelCount
      If I < 10 Then
      ActiveSheet.Range("C20").Value = "C906BGM0880000" & I
      ActiveSheet.PrintPreview
      Else
      ActiveSheet.Range("C20").Value = "C906BGM088000T" & I
      ActiveSheet.PrintPreview
      End If
    Next

以上操作无效。

Sub IncrementPrint()
'updateby Tyler Garretson
    Dim LabelCount As Variant
    Dim xScreen As Boolean
    Dim I As Long
    On Error Resume Next
LInput:
    LabelCount = Application.InputBox("Please enter the number of copies you want to print:")
    If TypeName(LabelCount) = "Boolean" Then Exit Sub
    If (ActiveSheet.Range("F11").Value = "") Or (ActiveSheet.Range("F14").Value = "") Or (ActiveSheet.Range("C18").Value = "") Then
        MsgBox "Error Occurred.  Please enter values for Route, Stop, and Destination Name", vbExclamation
    ElseIf (LabelCount = "") Or (Not IsNumeric(LabelCount)) Or (LabelCount < 1) Or (LabelCount > 999) Then
        MsgBox "Error Occurred. Please enter 1 - 999", vbExclamation
    ElseIf LabelCount < 10 Then
        xScreen = Application.ScreenUpdating
        Application.ScreenUpdating = False
        For I = 1 To LabelCount
          ActiveSheet.Range("C20").Value = "C906BGM0880000" & I
          ActiveSheet.PrintPreview
        Next

        ActiveSheet.Range("C20").ClearContents
        Application.ScreenUpdating = xScreen
    End If
End Sub

用户输入他或她希望打印的11个标签,程序将打印出以下内容:

Label1: ABC00001
Label2: ABC00002
Label3: ABC00003
Label4: ABC00004
Label5: ABC00005
Label6: ABC00006
Label7: ABC00007
Label8: ABC00008
Label9: ABC00009
Label10: ABC00010
Label11: ABC00011

2 个答案:

答案 0 :(得分:2)

您需要格式化命令-Format(1,“ 00000”)= 00001

Format(123,“ 00000”)= 00123

答案 1 :(得分:0)

'这可能是您需要的基础

for a = 1 to 1000
   b = right("0000000000" & a,8)  ' B will always be 8 long and paaded left with 0's
next a

这同样适用于文本前缀

for a = 1 to 1000
   c = "XYZ" & right("0000000000" & a,8)
next a