Home > Mobile >  Adding more variables/text to a label on VBA excel form
Adding more variables/text to a label on VBA excel form

Time:12-01

I am trying to make a label barcode generator on excel with VBA, but am running into some syntax issues. I managed to get a barcode to print, but I'd like to assign more variables under B2, like B3, B4, B5, B6, etc. and have that text display below or next to the barcode. It would be simple String variables assigned to each cell then just printed on the label once the button is pressed.

I tried looking up VBA syntax all day but am just running into errors. Does anyone know how I could get extra text added to this barcode? Below is the code I have attached to the button. The rest is just information on the excel sheet.

Sub Button2_Click()
    Const BarcodeWidth As Integer = 156
    Dim ws As Worksheet, WdApp
    
    
    Set ws = ActiveSheet
    
    With ws
        Range("B2").Select
    End With
    
    Set WdApp = CreateObject("Word.Application")
    With WdApp.Documents.Add
        .PageSetup.RightMargin = .PageSetup.PageWidth - .PageSetup.LeftMargin - BarcodeWidth
       
        .Fields.Add(Range:=.Range, Type:=-1, Text:="DISPLAYBARCODE " & CStr(Selection.Value) & " CODE39 \d \t", PreserveFormatting:=False).Copy
        
        
    End With
    ws.PasteSpecial Format:="Picture (Enhanced Metafile)", Link:=False, DisplayAsIcon:=False
    WdApp.Quit SaveChanges:=False
    Set WdApp = Nothing
End Sub

CodePudding user response:

It's not clear whether the additional text is supposed to be included in the barcode, or is just to appear below it. For the latter, try something along the lines of:

Sub Button2_Click()
Dim WdApp As Object, WdDoc As Object, StrCd As String, StrTxt As String
With ActiveSheet
  StrCd = Chr(34) & .Range("B2").Value & Chr(34)
  StrTxt = Chr(11) & .Range("B3").Value & " " & .Range("B4").Value & Chr(11) & .Range("B5").Value & " " & .Range("B6").Value
End With
Set WdApp = CreateObject("Word.Application"): Set WdDoc = WdApp.Documents.Add
With WdDoc
  .PageSetup.PageWidth = 180: .PageSetup.RightMargin = 36: .PageSetup.LeftMargin = 36
  .Fields.Add .Range, -1, "DISPLAYBARCODE " & StrCd & " CODE39 \d \t", False
  With .Range
    With .ParagraphFormat
      .Alignment = 1 'wdAlignParagraphCenter
      .LineSpacingRule = 0 'wdLineSpaceSingle
      .SpaceBefore = 0
      .SpaceAfter = 0
    End With
    .Characters.last.Text = StrTxt
    .Copy
  End With
  ActiveSheet.PasteSpecial Format:="Picture (Enhanced Metafile)", Link:=False, DisplayAsIcon:=False
  .Close False
End With
Set WdDoc = Nothing: WdApp.Quit: Set WdApp = Nothing
End Sub
  • Related