Excel VBA - 如果列没有设置值,则结束私有子

时间:2018-05-08 15:35:23

标签: excel vba excel-vba

我的宏存在问题。它将过滤列中的X条件,复制所有数据,然后粘贴到新工作表并保存。如果列中不存在X条件,它仍将继续保存为新工作表,并且工作表将为空并且文件大小很大。如何让VBA检查Y列中是否存在X条件,如果存在,则继续宏。否则,跳过整个私人子。

这是我遇到问题的部分。我想也许使用If-Else语句可能有效,但我不确定如何正确合并......就像如果第21列有“X”然后继续。否则,跳过整个子。

Private Sub SaveExternalCopy(ByVal Affiliate As String)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

dt = Format(DateAdd("m", -1, Now), "mm.yyyy")
Dim mhoWb As Workbook
Set mhoWb = Workbooks("All_" & dt & " " & " Macro Enabled")
Dim mhoSheet As Worksheet
Set mhoSheet = Sheets("MHO")
    mhoSheet.Activate
    mhoSheet.UsedRange.AutoFilter field:=21, Criteria1:=Affiliate & " " & "Recon"
With mhoSheet
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
End With

2 个答案:

答案 0 :(得分:0)

您可以在应用过滤器后检查可见行数:

{{1}}

答案 1 :(得分:0)

我想出了一个解决方法 - 它不是最漂亮的,它可能不是最有效但它至少起作用了!

Sub ShowAllData()

On Error Resume Next
Worksheets("My_Health_Online").ShowAllData

End Sub

Private Sub SaveExternalCopy(ByVal Affiliate As String)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim rngFoundCell As Range

dt = Format(DateAdd("m", -1, Now), "mm.yyyy")
Dim mhoWb As Workbook
Set mhoWb = Workbooks("All" & dt & " " & "Macro Enabled")
Dim mhoSheet As Worksheet
Set mhoSheet = Sheets("MHO")
    mhoSheet.Activate
    ShowAllData
    Set rngFoundCell = Sheets("MHO").Range("U2:U100000").Find(What:=Affiliate & " " & "Recon")

If rngFoundCell Is Nothing Then
        Exit Sub
Else

之后,我把剩下的代码放到正常运行的地方。此代码查看U列的X值。我不得不使用ShowAllData,因为我运行此代码5次,它创建了一个奇怪的情况,它没有在U列中找到任何值,因为它们在代码运行的前几次被过滤器隐藏。