我的代码结果有问题:主要的想法是我有一个单词模板,我从excel文件中复制粘贴不同的表 . 表格分为12个不同的表格,分别名为表1,表2等 . 当这些表格中有一些数据时,代码完美无缺 . 这是整个代码:
Sub CreateBasicWordReport()
'Create word doc automatically
Dim wApp As Word.Application
Dim SaveName As String
Set wApp = New Word.Application
With wApp
'Make word visible
.Visible = True
.Activate
.Documents.Add "C:\Users\MyDesktop\TemplateWordFile.dotx"
'paste supplier name in word
Sheets("Sheet1").Range("C1").Copy
.Selection.Goto what:=wdGoToBookmark, name:="SupplierName"
.Selection.PasteSpecial DataType:=wdPasteText
'Dynamic range
Dim Table1 As Worksheet
Dim Table2 As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set Table1 = Worksheets("Table 1")
Set Table2 = Worksheets("Table 2")
Set StartCell = Range("A1")
'Paste table 1 in word
Worksheets("Table 1").UsedRange
LastRow = Table1.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Table1.Range("A1:J" & LastRow).Copy
.Selection.GoTo what:=wdGoToBookmark, name:="Table1"
.Selection.PasteSpecial Link:=False, DataType:=wdPasteMetafilePicture, _
Placement:=wdAlignRowLeft, DisplayAsIcon:=True
'Paste table 2 in word
Worksheets("Table 2").UsedRange
LastRow = Worksheets("Table 2").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Worksheets("Table 2").Range("A1:J" & LastRow).Copy
.Selection.GoTo what:=wdGoToBookmark, name:="Table2"
.Selection.PasteSpecial Link:=False, DataType:=wdPasteMetafilePicture, _
Placement:=wdAlignRowLeft, DisplayAsIcon:=True
'Save doc to a specific location and with a specific title
Dim name As String
name = "C:\Users\MyDesktop\Supplier\" & "DocName" & "_" & _
Sheets("Sheet1").Range("C1").Value & "_" & Sheets("Sheet1").Range("H1").Value & _
"_" & Format(Now, "yyyy-mm-dd") & ".docx"
.ActiveDocument.SaveAs2 Filename:=name
End With
End Sub
问题是当纸张是空白时 . 我可能只需要一个表(来自表1)和IF下一个表(表2)是空的,然后我希望VBA什么也不做,然后转到下一步 . 但是在我的代码行中我得到运行时错误91:
LastRow = Worksheets("Table 2").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
我尝试了“on error resume next”命令,如下所示:
'Paste table 2 in word
Worksheets("Table 2").UsedRange
On Error Resume Next
LastRow = Worksheets("Table 2").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Worksheets("Table 2").Range("A1:J" & LastRow).Copy
.Selection.GoTo what:=wdGoToBookmark, name:="Table2"
.Selection.PasteSpecial Link:=False, DataType:=wdPasteMetafilePicture, _
Placement:=wdAlignRowLeft, DisplayAsIcon:=True
但在这种情况下,它确实给我的word文件带来了一个空表(五行,10行没有任何内容,只是表格的轮廓),而我只是想让它为空白/我的单词文件中没有任何内容 .
有人知道如何解决这个问题吗?
3 回答
您可以将
If Not IsEmpty(Table1.UsedRange) Then
语句添加到代码中 . 如果工作表完全为空,这将阻止代码运行 . 如果您需要更多帮助,请发表评论 .不幸的是我回答了,但他的建议可能会解决你的问题 . 我只是觉得你应该知道你的代码正在做什么 on "On Error Resume Next" is go to the next line, no matter if there is an error or not . 因此,为了告诉程序在出现错误时执行不同的操作,您必须验证错误是否发生并处理它 .
你可以通过将表cpying / pasting委托给特定的sub来避免一些代码重复并扩展你的代码应用程序:
相应地,您的主要代码将缩短为: