Excel VBA – 导出为PDF

首先,我是新来的,所以请客气。

我创build了一个摘要工作簿,它使用macros从文件夹中的多个工作簿中select特定范围(“A19:W105”),并将这些值复制到摘要工作簿中。 此范围内的数据量有所不同,有时可能为1行或多达86行。 代码运行良好,如下所示:

With wsMaster erow = .Range("B" & .Rows.Count).End(xlUp).Row wsTemp.Range("A19:W105").Copy .Range("B" & erow).Offset(1, 0).PasteSpecial xlPasteValues End With 

然后我创build了一个命令button将摘要工作簿保存为PDF。 我现在遇到的问题是,我写的代码select了所有已经复制的空白单元格。 这会导致一个PDF文件多页,即使只有1或2个页面中有实际的数据。 该代码如下:

 Dim lastrow As Long DateStr = Format(Date, "yyyy-mm-d") lastrow = Cells(Rows.Count, 2).End(xlUp).Row Range("B1:X" & lastrow).ExportAsFixedFormat Type:=xlTypePDF,_ Filename:="K:\AALI\Forecasts\Exported PDF Summary Sheets\"_ & "(" & DateStr & ") " & "MR Forecast and Budget Summary" & "_" _ & Comment, Quality:=xlQualityStandard, IncludeDocProperties:=True,_ IgnorePrintAreas:=False, OpenAfterPublish:=True 

有没有办法只select其中有实际信息的范围?

更新1:附件是工作表的屏幕截图。 在最后一行数据之下的所有东西都是“空白”(没有公式或文本),但是当macros从其他文件复制信息时,由于IFERROR公式的结果,某些值是空白的。 这是否有所作为? 另外,当复制数据时,我已经编写了一个sorting函数到macros,任何问题呢? 文件的屏幕截图

谢谢!

首先借助任何不包含任何空格的列来找出哪个数据是最后一个数据。 如果要使用Rows.count来获取上次使用的行,请确保已保存数据的完整表单为空(除数据外,应该没有任何内容)。

 Dim lastrow As Long If ActiveSheet.Range("B2").Value = "" Then lastrow = 2 Else lastrow = Range("B1").End(xlDown).Row End If Range("B1:X" & lastrow).Select Selection.ExportAsFixedFormat xlTypePDF, _ Filename:=ThisWorkbook.Path & "\Test.pdf" 

使用范围对象的列将不包含空白,而不是“B”,以find您的数据的结束,并更改PDF文件的位置和名称。

隐藏空行并将IgnorePrintAreas设置为True可以实现这一function。

 Dim x As Long, lastrow As Long Dim DateStr As String lastrow = Cells(Rows.Count, 2).End(xlUp).Row For x = 1 To lastrow If WorksheetFunction.CountA(Rows(x)) = 0 Then Rows(x).Hidden = True Next DateStr = Format(Date, "yyyy-mm-d") Range("B1:X" & lastrow).ExportAsFixedFormat Type:=xlTypePDF, _ FileName:="K:\AALI\Forecasts\Exported PDF Summary Sheets\" _ & "(" & DateStr & ") " & "MR Forecast and Budget Summary" & "_" _ & Comment, Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=True, OpenAfterPublish:=True