Excel 如何检查文件是否为空?
im使用以下代码作为excel宏-基本上它会遍历所有文件夹和子文件夹,并将找到的每个xls或xlsx文件保存为pdf格式。这很好,但是如果有一个空文件,它就会崩溃。如何检查我要转换为pdf的文件是否为空?或者有没有一种方法我也可以转换空文件?我对这两种解决方案都没意见 (我没有创建此代码,我找到了它,但对其进行了一些更改,我没有用VB编写代码) 谢谢你的帮助:)Excel 如何检查文件是否为空?,excel,vba,Excel,Vba,im使用以下代码作为excel宏-基本上它会遍历所有文件夹和子文件夹,并将找到的每个xls或xlsx文件保存为pdf格式。这很好,但是如果有一个空文件,它就会崩溃。如何检查我要转换为pdf的文件是否为空?或者有没有一种方法我也可以转换空文件?我对这两种解决方案都没意见 (我没有创建此代码,我找到了它,但对其进行了一些更改,我没有用VB编写代码) 谢谢你的帮助:) 尝试检查活动工作表中是否有值: 'your existing code Set objWorkbook = Applicati
尝试检查活动工作表中是否有值:
'your existing code
Set objWorkbook = Application.Workbooks.Open(objExcelFile.Path) 'existing
'new code lines______________
if objWorkbook.Sheets(1).cells.count > 0 then 'supposing that in not probable to have more sheets, but the first to be empty...
myPath = Replace(Replace(objFile.Path, ".xlsx", ""), ".xls", "")
objWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myPath & ".pdf"
end if
'End new code lines__________
objWorkbook.Close False
'your existing code
空工作簿!?
不完全确定使工作簿“空”的规则(假设),但您可以这样修改代码
Set objWorkbook = Application.Workbooks.Open(objExcelFile.Path)
If Not IsWorkbookEmpty(objWorkbook) Then
myPath = Replace(Replace(objFile.Path, ".xlsx", ""), ".xls", "")
objWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=myPath & ".pdf"
End If
objWorkbook.Close False
。。。它利用了以下功能:
Function IsWorkbookEmpty(ByVal wb As Workbook) As Boolean
If wb Is Nothing Then IsWorkbookEmpty = True
' Assumptions:
' 1. There are only workheets and/or charts in the workbook.
' 2. A workbook is empty if all the cells of its visible worksheets
' are empty and there are no visible charts.
Dim sh As Object
Dim fCell As Range
For Each sh In wb.Sheets
If sh.Visible = xlSheetVisible Then
If sh.Type = xlWorksheet Then
Set fCell = Nothing
Set fCell = sh.Cells.Find("*", sh.Cells(sh.Rows.Count, _
sh.Columns.Count), xlFormulas, , xlByRows)
If Not fCell Is Nothing Then
Exit Function
End If
Else
Exit Function
End If
End If
Next sh
IsWorkbookEmpty = True
End Function
空文件和它崩溃意味着什么?具体点。您使用的是哪个版本的Office
?
Function IsWorkbookEmpty(ByVal wb As Workbook) As Boolean
If wb Is Nothing Then IsWorkbookEmpty = True
' Assumptions:
' 1. There are only workheets and/or charts in the workbook.
' 2. A workbook is empty if all the cells of its visible worksheets
' are empty and there are no visible charts.
Dim sh As Object
Dim fCell As Range
For Each sh In wb.Sheets
If sh.Visible = xlSheetVisible Then
If sh.Type = xlWorksheet Then
Set fCell = Nothing
Set fCell = sh.Cells.Find("*", sh.Cells(sh.Rows.Count, _
sh.Columns.Count), xlFormulas, , xlByRows)
If Not fCell Is Nothing Then
Exit Function
End If
Else
Exit Function
End If
End If
Next sh
IsWorkbookEmpty = True
End Function