以下是从特定工作表中编译数据的代码"按位置修复摘要"将多个工作簿放入宏书工作表"修复摘要"。
有些工作簿上没有任何关于"按位置修复摘要"的数据。宏应该什么都不做,但跳到下一个工作簿。
此外,如果工作表存在,但它是空的,那么宏也应该如上所述。以下是代码。
</body>
答案 0 :(得分:1)
这是@Tim的解决方案的替代方案:
Public Function getSheet(ByVal wsName As String, Optional wb As Workbook = Nothing) As Worksheet
Dim ws As Worksheet
If Len(wsName) > 0 Then
If wb Is Nothing Then Set wb = ActiveWorkbook
For Each ws In wb.Worksheets
If ws.Name = wsName Then
Set getSheet = ws
Exit Function
End If
Next
End If
End Function
并检查该表是否存在且不为空:
Dim ws As Worksheet
Set ws = getSheet("Repair Summary by Location")
If Not ws Is Nothing Then 'validates if Worksheet exists
If WorksheetFunction.CountA(ws) > 0 Then 'validates if Worksheet is not empty
...
答案 1 :(得分:1)
请参阅上面链接中@ rory的回答。将它与Application.WorksheetFunction.CountA()一起使用并组合它们......只需4行代码......
继我的评论之后,这里有4行代码
If Evaluate("ISREF('" & sName & "'!A1)") Then '<~~ If sheet exists
If Application.WorksheetFunction.CountA(Sheets(sName).Cells) > 0 Then '<~~ If not empty
'
'~~> Your code
'
End If
End If
答案 2 :(得分:0)
你可以在接下来的错误恢复,但我会建议反对一揽子解决方案。我会在打开书籍时使用循环来查找使用函数的工作表。像这样:
Function FoundSheet(MySheetName as string) As Boolean
Dim WS as Worksheet
FoundSheet = False
For each WS in worksheets
If WS.Name = MySheetName then
FoundSheet = True
Exit for
End if
Next
End Function
此函数返回true或false(As Boolean),您可以在代码中使用它,如下所示:
If FoundSheet("YourSheetName") then 'Don't need = True or = False on the test as it is a boolean
'Your code goes here Start with a test, select it then see if there is data
End if
我自由手输入代码,所以可能有一两个错字但我相信你可以调试它。
以下是一个非常粗略的示例,说明它是如何工作的(我在新的工作簿上运行了Sheet1和Sheet2但没有Sheet3):
Sub testFunc()
Dim X As Long
For X = 1 To 3
MsgBox "Sheet" & X & " exists: " & FoundSheet("Sheet" & X)
Next
End Sub