简体   繁体   中英

Have an Excel macro skip lines if a cell is blank

I'm nearing the end of this macro I'm developing for the processing of text reports, but I'm not sure how to ignore when the reports I'm pulling in are blank.

What occurs is that the text file is pulled in, and while there is some data in the text file, it's not relevant to what I need to extract. I've identified that Sheet1.Range("A5") will be blank if the report is blank for my purposes, but I'm not sure how to tell the macro to skip the steps where I've left the comment "Copy values to main data table".

Effectively, I want to go through the process all the way up to that comment, and then I need for the macro to look at Sheet1.Range("A5") . If it's blank, then I want it to skip ahead to the Sheet6.Activate line and carry on executing.

Do I just put an If statement before the copy?

Sub Import()

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

' Variables for paths and filename

Dim currentPath As String
Dim newPath As String
Dim currentFile As String

currentPath = "\\Unprocessed\"
newPath = "\\Processed\"

' Get the first file

    currentFile = Dir(currentPath & "*.txt")
    Do While currentFile <> ""

' Clear previous data

    Sheet1.Activate
    ActiveSheet.UsedRange.Clear
    Range("A1").Select

' Process text file

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & currentPath & currentFile, _
        Destination:=Range("$A$1"))
        .Name = "Data"
        .FieldNames = True
        .TextFileTabDelimiter = True
        .TextFileColumnDataTypes = Array(3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .Refresh BackgroundQuery:=False
    End With

    ActiveSheet.QueryTables(1).Delete

' Copy values to main data table

    Sheet3.Range("A2:Q2").Copy
    Sheet6.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    Sheet6.Activate

' Move file into Processed folder

    Name currentPath & currentFile As newPath & currentFile

' Get the next file

    currentFile = Dir
    Loop

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub

An IF statement should do it:

If Sheet1.Range("A5") <> "" then 'if A5 is not blank then do the following
    Sheet3.Range("A2:Q2").Copy
    Sheet6.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
    Sheet6.Activate
End if

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM