简体   繁体   中英

VBA macro to export XML which avoids a row if a certain cells is “OFF” value

I have a VBA macro that prints my data out as an XML. I'm trying to figure out a way to edit my macro to skip a row during the loop if a certain cell value is "OFF". Since I'm not great at writing VBA code, I wanted to keep this simple so I look up vba macros and fiddle with them until I get the desired result so apologies for any mistakes I have in the code provided. Here's the macro I have now but I keep getting a mismatch type error. For each row of the XML, I have a cell next to it that is either set to the "ON" or "OFF" value. Thanks for the help everyone!

Sub Export_tvXML()

Dim XMLFileName As String

Dim MetaFileName1 As String
Dim MetaFileName2 As String

Dim output1 As String
Dim output2 As String

Dim range1 As Range
Dim range2 As Range

Set range1 = Sheets("XML").Range("A2:E84")
Set range2 = Sheets("XML").Range("A86:E168")

MetaFileName1 = Sheets("TV_Info").Range("G5")
MetaFileName2 = Sheets("TV_Info").Range("G6")


XMLFileName = MetaFileName1 & ".xml"

For Each r In range1.Rows
    If Cells(r, 6).Value = 1 Then
        For Each c In r.Cells
            output1 = output1 & c.Value
        Next c
        output1 = output1 & vbNewLine
    End If
Next r

Open XMLFileName For Output As #1
Print #1, output1
Close #1


XMLFileName = MetaFileName2 & ".xml"

For Each r In range2.Rows
    For Each c In r.Cells
        output2 = output2 & c.Value
    Next c
    output2 = output2 & vbNewLine
Next r

Open XMLFileName For Output As #2
Print #2, output2
Close #2


End Sub

As for the spreadsheet side of it, I have mocked up XMLs and the macro will just output the value as it's formatted. Here's a screenshot for reference. So any row that is set to off, I want the macro to skip that row and move onto to the next row that's on to output it.

XML Mockup

I think your problem is in the following line:

If Cells(r, 6).Value = 1 Then

You are testing the cell value against a number (1), but you mean to test against a string value, which is why you get the type mismatch.

Try changing it to the following:

If StrComp(Cells(r, 6).Value,"ON")=0 Then

StrComp is a useful function to compare two strings, which includes options to make the comparison case-insensitive. In this case, the two strings are the contents of successive cells in column 6, and the string "ON".

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