我写了这段代码,但它不起作用。我正在寻求有关 Word 部分的帮助。 我有两个问题:我无法为每个 Excel 单元格生成新页面,并且 code128 没有垂直和水平居中对齐。
Sub CreateBarcode4()
' Declare variables
Dim ws As Worksheet
Dim wd As Object
Dim doc As Object
Dim rng As Range
Dim cell As Range
Dim barcode As Object
Dim text As String
' Set the Excel sheet to read values from
Set ws = ThisWorkbook.Sheets("Sheet1")
' Create a new Word document
Set wd = CreateObject("Word.Application")
wd.Visible = True
Set doc = wd.Documents.Add
' Set the page format to 10cm x 5cm
With doc.PageSetup
.PaperSize = wdPaperCustom
.PageWidth = CentimetersToPoints(10)
.PageHeight = CentimetersToPoints(5)
.Orientation = wdOrientLandscape
.VerticalAlignment = wdAlignVerticalCenter 'Added to vertically align the content of the page
End With
' Set the range to read values from
Set rng = ws.Range("A1", ws.Range("A" & ws.Rows.Count).End(xlUp))
' For each non-empty cell in the range
For Each cell In rng
If cell.Value <> "" Then
' Insert a new page in the Word document
doc.Range.InsertBreak Type:=wdPageBreak
' Add the text as the result of the field
text = "DisplayBarcode " & Chr(34) & cell.Value & Chr(34) & " CODE128 \t"
' Add the field to the end of the document
doc.Fields.Add Range:=doc.Range(doc.Range.End - 1), Type:=wdFieldEmpty, Text:=text, PreserveFormatting:=False
' Modify the alignment
doc.Paragraphs(doc.Paragraphs.Count).Alignment = 1 ' wdAlignParagraphCenter
' Modify to hide field codes
wd.ActiveWindow.View.ShowFieldCodes = False
End If
Next cell
End Sub
屏幕截图:
请尝试一下。
Option Explicit
Sub CreateBarcode4()
' Declare variables
Dim ws As Worksheet
Dim wd As Object
Dim doc As Word.Document
Dim rng As Range
Dim cell As Range
Dim barcode As Object
Dim text As String
' Set the Excel sheet to read values from
Set ws = ThisWorkbook.Sheets("Sheet1")
' Create a new Word document
' Set wd = CreateObject("Word.Application")
Set wd = GetObject(, "Word.Application")
wd.Visible = True
Set doc = wd.Documents.Add
' Set the page format to 10cm x 5cm
With doc.PageSetup
.PaperSize = wdPaperCustom
.TopMargin = 36
.BottomMargin = 36
.PageWidth = CentimetersToPoints(10)
.PageHeight = CentimetersToPoints(5)
' .Orientation = wdOrientLandscape
.VerticalAlignment = wdAlignVerticalCenter 'Added to vertically align the content of the page
End With
' Set the range to read values from
Set rng = ws.Range("A1", ws.Range("A" & ws.Rows.Count).End(xlUp))
' For each non-empty cell in the range
For Each cell In rng
If cell.Value <> "" Then
' Add the text as the result of the field
text = "DisplayBarcode " & Chr(34) & cell.Value & Chr(34) & " CODE128 \t"
' Add the field to the end of the document
doc.Fields.Add Range:=doc.Range(doc.Range.End - 1), Type:=wdFieldEmpty, text:=text, PreserveFormatting:=False
' Modify the alignment
doc.Paragraphs(doc.Paragraphs.Count).Alignment = 1 ' wdAlignParagraphCenter
' Modify to hide field codes
wd.ActiveWindow.View.ShowFieldCodes = False
wd.Selection.EndKey wdStory
End If
Next cell
End Sub