copy sheet to text file with specific template skips even numbers - excel

I want to copy sheet to text file with specific template, I defined a range but the problem is it skips even numbers it means rows A2, A4,A6... not copied
so it brings at the end of the result empty rows
Option Explicit
Sub txtFile()
Dim strPath As String
Dim fso As Object
Dim ts As Object
Dim wsDest As Worksheet
Set wsDest = Sheets("Filter FS")
wsDest.Select
Set fso = CreateObject("Scripting.FileSystemObject")
Dim cellAimsID As Variant
Dim cellAmount As Variant
Dim cellCurrencyISO As Variant
Dim cellReason As Variant
Dim cellExpiryDate As Variant
Dim FirstRow As String
Dim LastRow As String
Dim a As Range, b As Range, cell As String, rng As Range
Set a = Selection
Set ts = fso.CreateTextFile("C:\Users\cben\Documents\BKC\FinancialSecurity\test13.txt", True, True)
' for each cell in the worksheet create a line in text fil
FirstRow = wsDest.UsedRange.Rows(1).Row
LastRow = wsDest.Range("A" & Rows.Count).End(xlUp).Row
Set rng = wsDest.Range("A2:A" & LastRow)
'Set rng = wsDest.Range("A1:A5")
For Each a In rng
cellAimsID = a.Cells(a.Row, 1)
cellAmount = a.Cells(a.Row, 2)
cellCurrencyISO = a.Cells(a.Row, 3)
cellReason = a.Cells(a.Row, 4)
cellExpiryDate = a.Cells(a.Row, 5)
'AimsID, Amount, Currency, Reason, ExpiryDate are the name of columns in worksheet
ts.WriteLine (Chr(9) & "cases" & ": [")
ts.WriteLine (Chr(9) & "{")
ts.WriteLine (Chr(9) & "AimsID:" & cellAimsID & ",")
ts.WriteLine (Chr(9) & "Amount:" & cellAmount & ",")
ts.WriteLine (Chr(9) & "CurrencyISO:" & cellCurrencyISO & ",")
ts.WriteLine (Chr(9) & "Reason:" & cellReason & ",")
ts.WriteLine (Chr(9) & "ExpiryDate:" & cellExpiryDate & ",")
ts.WriteLine (Chr(9) & "}" & ",")
Next
ts.Close
End Sub
here is the result
for exemple AimsID= 69210794 correspond to A41 next AimsID =86917526 corresponds to A43 not A42 in the result

The problem lies in your For Each loop as detailed below.
For Each a In rng
cellAimsID = a.Cells(a.Row, 1)
cellAmount = a.Cells(a.Row, 2)
cellCurrencyISO = a.Cells(a.Row, 3)
cellReason = a.Cells(a.Row, 4)
cellExpiryDate = a.Cells(a.Row, 5)
In this loop, the variable a refers to a Range object. Yet, inside of the loop, you assign to each variable a Range property of a Range object. Let's take a closer look as an example:
`cellAimsID = a.Cells(a.Row, 1)
Let's assume you are on the second iteration of the loop, and the variable a refers to cell A3. The syntax above says cellsAimsID = Range("A3").Range("A3"). What happens when we apply a Range property to a Range object? It basically offsets cell. In that above example, the cell pointer essentially moves to a cell that would be the third cell in Column A IF the range started with A3.
I know that sounds a bit confusing, but follow up if you have questions.
To fix the error, replace the syntax with (notice I removed the a qualifier):
cellAimsID = Cells(a.Row, 1)
cellAimsID = Cells(a.Row, 1)
As a side note, it is a good practice to fully qualify your ranges with a sheet name in case your macro ever does processing on different sheets. So it would be even better to change the code to:
cellAimsID = wsDest.Cells(a.Row, 1)
cellAimsID = wsDest.Cells(a.Row, 1)

This is my code after changes,
It allows the export of a worksheet in text file with specific template.
PS : Last line have a close Array so I did it outside the range.
Option Explicit
Sub txtFile()
Dim strPath As String
Dim fso As Object
Dim ts As Object
Dim wsDest As Worksheet
Set wsDest = Sheets("Filter FS")
wsDest.Select
Set fso = CreateObject("Scripting.FileSystemObject")
Dim cellAimsID As Variant
Dim cellAmount As Variant
Dim cellCurrencyISO As Variant
Dim cellReason As Variant
Dim cellExpiryDate As Variant
Dim FirstRow As String
Dim LastRow As String
Dim LastRowB As String
Dim a As Range, b As Range, cell As String, rng As Range, Lastrng As Range
Set a = Selection
Set ts = fso.CreateTextFile("C:\Users\cben\Documents\BKC\FinancialSecurity\test20.txt", True, True)
' for each cell in the worksheet create a line in text fil
FirstRow = wsDest.UsedRange.Rows(1).Row
LastRow = wsDest.Range("A" & Rows.Count).End(xlUp).Row
LastRowB = (wsDest.Range("A" & Rows.Count).End(xlUp).Row) - 1
Set rng = wsDest.Range("A2:A" & LastRowB)
Set Lastrng = wsDest.Range("A" & LastRow)
ts.WriteLine ("{")
ts.WriteLine (Chr(9) & "“cases”" & ": [")
For Each a In rng
cellAimsID = Cells(a.Row, 1)
cellCurrencyISO = Cells(a.Row, 2)
cellAmount = Cells(a.Row, 3)
cellReason = Cells(a.Row, 4)
cellExpiryDate = Cells(a.Row, 5)
'AimsID, Amount, Currency, Reason, ExpiryDate are the name of columns in worksheet
ts.WriteLine (Chr(9) & "{")
ts.WriteLine (Chr(9) & "“AimsID”" & ":" & Chr(9) & cellAimsID & ",")
ts.WriteLine (Chr(9) & "“Amount”" & ":" & Chr(9) & cellAmount & ",")
ts.WriteLine (Chr(9) & "“CurrencyISO”" & ":" & Chr(9) & cellCurrencyISO & ",")
ts.WriteLine (Chr(9) & "“Reason”" & ":" & Chr(9) & cellReason & ",")
ts.WriteLine (Chr(9) & "“ExpiryDate”" & ":" & Chr(9) & "“" & cellExpiryDate & "”")
ts.WriteLine (Chr(9) & "}" & ",")
Next
cellAimsID = Cells(LastRow, 1)
cellCurrencyISO = Cells(LastRow, 2)
cellAmount = Cells(LastRow, 3)
cellReason = Cells(LastRow, 4)
cellExpiryDate = Cells(LastRow, 5)
ts.WriteLine (Chr(9) & "{")
ts.WriteLine (Chr(9) & "“AimsID”" & ":" & Chr(9) & cellAimsID & ",")
ts.WriteLine (Chr(9) & "“Amount”" & ":" & Chr(9) & cellAmount & ",")
ts.WriteLine (Chr(9) & "“CurrencyISO”" & ":" & Chr(9) & cellCurrencyISO & ",")
ts.WriteLine (Chr(9) & "“Reason”" & ":" & Chr(9) & cellReason & ",")
ts.WriteLine (Chr(9) & "“ExpiryDate”" & ":" & Chr(9) & "“" & cellExpiryDate & "”")
ts.WriteLine (Chr(9) & "}" & "]")
ts.WriteLine ("}")
ts.Close
End Sub

Related

How to handle double quotes in vba

I have a string assigned to variables and need to declare that in cell using vba.
I tried below code and throws error
Dim Var2,Str as string
Var1="OD"
Var2="Leave"
Str="Employee":Var2,"Type":Var1
set ws=ActiveWorkbook.Worksheets("Sheet1")
ws.cells(2,4).value=str
My expected output in cells(2,4) should be "Employee":"Leave","Type":"OD"
My expected output in cells(2,4) should be "Employee":"Leave","Type":"OD"
Store the values in an array. It will be much easier to handle as compared to having so many variables.
You can use Chr(34) for ". Is this what you are trying?
Option Explicit
Sub Sample()
Dim Ar(1 To 4) As String
Dim Strg As String
Dim ws As Worksheet
Ar(1) = "OD"
Ar(2) = "Type"
Ar(3) = "Leave"
Ar(4) = "Employee"
'"Employee":"Leave","Type":"OD"
Strg = Chr(34) & Ar(4) & Chr(34)
Strg = Strg & ":" & Chr(34) & Ar(3) & Chr(34)
Strg = Strg & "," & Chr(34) & Ar(2) & Chr(34)
Strg = Strg & ":" & Chr(34) & Ar(1) & Chr(34)
'Debug.Print Strg
Set ws = ActiveWorkbook.Worksheets("Sheet1")
ws.Cells(2, 4).Value = Strg
End Sub

What is causing my code to have 1004 runtime error

I know this code is a mess but it's been at least working with no errors for weeks. The directories of all the files in question exist.
'''
Sub NEW_PO()
'''''''''''''''''''''''''''''''''''Declare Variables''''''''''''''''''''''''''''''''''''''''''''
Dim disc As String
Dim New_Data_Column As Long 'last date ordered column (number)
Dim NewPO_num As String 'New_Data_Column - 10 (needs leading "0" for single digits)
Dim Job_Num As String '= C2
Dim Cost_Code As String '= Active sheet name
Dim lastCol As String 'last date ordered column (Letter)
Dim sht As Worksheet
Dim lastRow As Long 'last row of description column
Set sht = ActiveSheet
''''''''''''''''''''''Find last row and column(letter)''''''''''''''''''''''''''''''''''''''''''
New_Data_Column = Cells(8, Columns.count).End(xlToLeft).Column
lastCol = Split(Columns(Range("A8").End(xlToRight).Column).Address(, False), ":")(1)
lastRow = sht.Cells(sht.Rows.count, 3).End(xlUp).Row
'''''''''''''''''''''''''''''Check for Data'''''''''''''''''''''''''''''''''''''''''''''''''''''
If WorksheetFunction.CountA(Range(lastCol & "11:" & lastCol & lastRow)) = 0 Then
MsgBox "Error! Please enter data to continue."
Exit Sub
ElseIf WorksheetFunction.CountA(Range(lastCol & "10")) = 0 Then
MsgBox "Error! Please enter date to continue."
Range(lastCol & "10").Select
Exit Sub
Else
''''''''''''''''''''''''''''''''Propmt for description of PO''''''''''''''''''''''''''''''''''''
disc = InputBox("Please enter a description for this Purchase Order.", "New Purchase Order")
If disc = "" Then
MsgBox "You Must Enter A Description!"
Exit Sub
End If
''''''''''''''''''''''''''''''''''Set Cost Code''''''''''''''''''''''''''''''''''''''''''''''''
Cost_Code = sht.name
'''''''''''''''''''''''''''''''''Set Job Number''''''''''''''''''''''''''''''''''''''''''''''''
Job_Num = sht.Cells(2, 4).Text 'as text to keep formatting
'''''''''''''''''''''''''''''Set New Purchase Order Number'''''''''''''''''''''''''''''''''''''
sht.Range("A4").Value = sht.Range("A4").Value + 1
If sht.Range("A4").Value < 10 Then
NewPO_num = "0" & sht.Range("A4").Value
Else
NewPO_num = sht.Range("A4").Value
End If
''''''''''''Open PO Template and save as PO number & Copy PO to S/R Log''''''''''''''''''''
Dim sPath As String
sPath = Application.ThisWorkbook.path
Dim i As Integer
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Dim lastPO_row As Long
Dim lastSR_row As Long
Dim wkb3 As Workbook
Dim sht3 As Worksheet
Dim sht4 As Worksheet
Application.ScreenUpdating = False
Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open(sPath & "\1 CONSTRUCTION\Purchase Orders\Purchase Order Template.xlsm")
Set wkb3 = Workbooks.Open(sPath & "\1 CONSTRUCTION\RECEIVED MATERIALS\SR Log.xlsx")
Set sht1 = wkb1.Sheets(Cost_Code)
Set sht2 = wkb2.Sheets("Sheet1")
Set sht3 = wkb3.Sheets("Sheet1")
Set sht4 = wkb2.Sheets("Job Addresses")
'''
This is where the error is occurring. Normally it would save the template as specified with no problems. I have deleted the code and written it in notepad and pasted it back into excel and it still gives an error. I've tried on multiple computers with the same result. I even uninstalled and reinstalled office and still not working.
'''
wkb2.SaveAs (sPath & "\1 CONSTRUCTION\Purchase Orders\" & Cost_Code & "\" & Job_Num & "-" & NewPO_num
& "-" & Cost_Code & " " & disc & ".xlsm")
wkb3.SaveAs (sPath & "\1 CONSTRUCTION\RECEIVED MATERIALS\" & Cost_Code & "\" & Job_Num & "-" &
NewPO_num & "-" & Cost_Code & " " & disc & ".xlsx")
sht2.name = Job_Num & "-" & NewPO_num & "-" & Cost_Code & " " & disc
lastPO_row = sht2.Cells(sht.Rows.count, 3).End(xlUp).Row + 1
lastSR_row = sht3.Cells(sht.Rows.count, 1).End(xlUp).Row + 1
''''''''''''Copy relevant entries to PO sheet and Shipping/Receiving Log'''''''''''''''''''
For i = 11 To lastRow
If sht1.Cells(i, New_Data_Column).Value <> "" Then
sht1.Range(lastCol & i).Copy
sht2.Range("A" & lastPO_row).PasteSpecial xlPasteValues
sht3.Range("D" & lastSR_row).PasteSpecial xlPasteValues
sht1.Range("B" & i & ":C" & i).Copy
sht2.Range("B" & lastPO_row & ":C" & lastPO_row).PasteSpecial xlPasteValues
sht3.Range("A" & lastSR_row & ":B" & lastSR_row).PasteSpecial xlPasteValues
lastPO_row = lastPO_row + 1
lastSR_row = lastSR_row + 1
End If
Next
sht2.Range("E6").Value = wkb1.Sheets("PM Dashboard").Range("O3").Value
sht2.Range("E7").Value = Job_Num & "-" & NewPO_num & "-" & Cost_Code
sht2.Range("E8").Value = Dashboard.Sheets("PM Dashboard").Range("Y2").Value
'add this job's address to list of addresses on PO
sht4.Range("A7").Value = wkb1.Sheets("PM Dashboard").Range("O3").Value & vbNewLine _
& wkb1.Sheets("PM Dashboard").Range("AP3").Value & vbNewLine & wkb1.Sheets("PM
Dashboard").Range("AP4").Value
wkb2.Save
sht3.Range("C1").Value = Job_Num & "-" & NewPO_num & "-" & Cost_Code & " " & disc
wkb3.Save
wkb3.Close
'''''''''''''''''''''copy over last column and hide previous'''''''''''''''''''''
sht1.Columns(New_Data_Column).Copy
sht1.Columns(New_Data_Column + 1).PasteSpecial Paste:=xlPasteFormats
sht1.Range(lastCol & "8:" & lastCol & "9").Copy
sht1.Range(lastCol & "8:" & lastCol & "9").Offset(0, 1).PasteSpecial Paste:=xlPasteValues
Call HIDE
wkb1.Save
Application.ScreenUpdating = True
End If
End Sub
'''

Generate XML File with VBA

I'm trying to generate an XML file with VBA code.
My goal is to alter Excel data, and then to export this data into a valid XML file. There's only one row of data and one row for the name of the tags which I want to have the data inside.
How can I run through all the data and generate an XML file?
Some sample data (My original file has more columns and data).
(The yellow data is my first block in XML and the green data my second block.)
Here's how the XML File should look:
<?xml version="1.0" encoding="UTF-8"?>
<NmLoader>
<csvBeginTypeDefView handler ="TypeDefinition">
<csvattTemplate>LW</csvattTemplate>
<csvnameSpace>default</csvnameSpace>
<csvname>Tires</csvname>
<csvcontainerDomain/>
<csvtypeParent>Wheels</csvtypeParent>
</csvBeginTypeDefView>
<csvBeginAttributeDefView handler = "AttributeDefinition">
<csvname>TiresAT</csvname>
<csvattDefClass>Definition</csvattDefClass>
<csvdatatype>String</csvdatatype>
<csvIBA>TiresAT</csvIBA>
<csvQoM/>
</csvBeginAttributeDefView>
</NmLoader>
My Code:
Public Sub GenerateXML()
Dim sht As Worksheet
Dim loLetzteZ As Long, loLetzteS As Long, i As Long
Dim rBereich As Range, rng As Range
Dim sTagO As String, sTagC As String, sTagOEnd As String, sTagCStart As String
Dim sZeile As String
Dim strPfad As String
Dim strText As String
sTagO = "<"
sTagOEnd = "/>"
sTagC = ">"
sTagCStart = "</"
Set sht = Worksheets("Data")
'determine the last possible row
loLetzteZ = sht.Cells(Rows.Count, 1).End(xlUp).Row
'determine the last possible column
loLetzteS = sht.Cells(1, Columns.Count).End(xlToLeft).Column
'set me the area for the complete worksheet
Set rBereich = sht.Range("A2:" & Cells(loLetzteZ, loLetzteS).Address)
Application.ScreenUpdating = False
strPfad = ActiveWorkbook.Path & "\Data" & ".xml"
'row for row
For Each rng In rBereich.Rows
With rng
'column for column
For i = 1 To .Columns.Count
'If the tag is empty, then close this
If IsEmpty(.Cells(1, i)) Then
sZeile = sZeile & sTagO & Cells(1, i) & sTagOEnd
Else
'Opening Tag
sZeile = sZeile & sTagO & Cells(1, i) & sTagC
'Data for the tags
sZeile = sZeile & .Cells(1, i)
'End of Tags
sZeile = sZeile & sTagCStart & Cells(1, i) & sTagC
End If
'Write line with distance
sZeile = sZeile & vbCrLf
Next
'Write line with distance
sZeile = sZeile & vbCrLf & vbCrLf
'Open file and write the text
Call InDateiSchreiben(strPfad, sZeile, True)
End With
Next
Application.ScreenUpdating = True
End Sub
Other Solutions I tried:
I've already mapped the XML with Excel, but Excel is not able to export such an XML Schema.
I wrote code in VBA (I'm a beginner) by looking through posts regarding an XML Export.
Try this
Function GetXmlElement(sTagName As String, _
sValue As String, _
Optional bUseEmptyTags As Boolean = False, _
Optional bMultiline As Boolean = False) As String
Dim sStartOpen As String: sStartOpen = "<"
Dim sClose As String: sClose = ">"
Dim sEndOpen As String: sEndOpen = "</"
Dim sEmptyClose As String: sEmptyClose = " />"
Dim sTab As String: sTab = " "
Dim sTagValSeparator As String
Dim sValTagSeparator As String
If bMultiline Then
sTagValSeparator = Chr(10) & sTab
sValTagSeparator = Chr(10)
End If
If Len(sValue) = 0 And bUseEmptyTags Then
GetXmlElement = sStartOpen & sTagName & sEmptyClose
Else
GetXmlElement = sStartOpen & sTagName & sClose & sTagValSeparator & _
Replace(sValue, Chr(10), Chr(10) & sTab) & _
sValTagSeparator
If InStr(1, sTagName, " ") > 0 Then
'tag has attributes'
sTagName = Left(sTagName, InStr(1, sTagName, " ") - 1)
End If
GetXmlElement = GetXmlElement & sEndOpen & sTagName & sClose
End If
End Function
Function GetXMLOutput() As String
Dim lLastCol As Long
Dim i As Long
Dim lCsvBeginCol As Long
Dim sTagName As String
Dim sInnerElements As String
Dim sOutput As String
With ThisWorkbook.Sheets("Data")
lLastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
lCsvBeginCol = 1
For i = 1 To lLastCol
sTagName = .Cells(1, i)
If Left(sTagName, 8) = "csvBegin" And i > lCsvBeginCol Or i = lLastCol Then
' build the outer element
sTagName = .Cells(1, lCsvBeginCol) & "=""" & .Cells(2, lCsvBeginCol) & """"
If Len(sOutput) > 0 Then
sOutput = sOutput & Chr(10) & Chr(10)
End If
sOutput = sOutput & GetXmlElement(sTagName, sInnerElements, True, True)
lCsvBeginCol = i
sInnerElements = ""
ElseIf i <> lCsvBeginCol Then
' build the inner elements
If Len(sInnerElements) > 0 Then sInnerElements = sInnerElements & Chr(10)
sInnerElements = sInnerElements & GetXmlElement(sTagName, .Cells(2, i), True)
End If
Next i
sOutput = GetXmlElement("NmLoader", sOutput, True, True)
sOutput = "<?xml version=""1.0"" encoding=""UTF-8""?>" & Chr(10) & Chr(10) & sOutput
GetXMLOutput = sOutput
Debug.Print sOutput
End With
End Function
Sub GenerateXML()
Dim sFilename As String
sFilename = ThisWorkbook.Path & "\Data.xml"
Open sFilename For Output As #1
Print #1, GetXMLOutput
Close #1
End Sub
Try
Option Explicit
Public Sub GenerateXML()
Dim sht As Worksheet
Set sht = Worksheets("Data")
Dim loLetzteZ As Long, loLetzteS As Long, i As Long
Dim rBereich As Range, rng As Range
Dim sZeile As String
Dim strPfad As String
Dim sTag As String, sTag1 As String, sData As String
'determine the last possible row
loLetzteZ = sht.Cells(Rows.Count, 1).End(xlUp).Row
'determine the last possible column
loLetzteS = sht.Cells(1, Columns.Count).End(xlToLeft).Column
'set me the area for the complete worksheet
Set rBereich = sht.Range("A2:" & Cells(loLetzteZ, loLetzteS).Address)
' output
strPfad = ActiveWorkbook.Path & "\Data" & ".xml"
sTag1 = ""
sZeile = "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCrLf _
& "<NmLoader>" & vbCrLf
'row for row
For Each rng In rBereich.Rows
With rng
'column for column
For i = 1 To .Columns.Count
sTag = Trim(sht.Cells(1, i))
sData = Trim(.Cells(1, i))
'If the tag is handler
If LCase(Right(sTag, 7)) = "handler" Then
sTag1 = Split(sTag, " ")(0) ' remove handler
sZeile = sZeile & "<" & sTag1 & " handler=""" & sData & """>"
' is it a closing tag
ElseIf sTag = sTag1 Then
sZeile = sZeile & "</" & sTag1 & ">" & vbCrLf
ElseIf Len(sData) > 0 Then
sZeile = sZeile & vbTab & "<" & sTag & ">" & sData & "</" & sTag & ">"
Else
sZeile = sZeile & vbTab & "<" & sTag & "/>"
End If
sZeile = sZeile & vbCrLf
Next
'Write line with distance
sZeile = sZeile & vbCrLf & "</NmLoader>" & vbCrLf
'Open file and write the text
Debug.Print sZeile
'Call InDateiSchreiben(strPfad, sZeile, True)
End With
Next
MsgBox strPfad & " created", vbInformation
End Sub

Loop through cells of all Excel Worksheets to generate one XML file

I have 10 sheets. I wrote some code to go through all the data inside a sheet and create an XML file as an output.
I have to click the button each time at each sheet and then I have 10 different XML files. I want one button in one sheet, let's call it Description, to go through all my sheets and create one file with all the XML data.
I tried to use a for each loop. Instead of reading all the sheets, it reads only the first sheet for many times.
Sub XMLTextdatei()
Dim sht As Worksheet
Dim loLetzteZ As Long, loLetzteS As Long, I As Long
Dim rBereich As Range, rng As Range
Dim sTagO As String, sTagC As String, sTagOEnd As String, sTagCStart As String
Dim sZeile As String
Dim strPfad As String
Dim strText As String
sTagO = "<"
sTagOEnd = "/>"
sTagC = ">"
sTagCStart = "</"
Set sht = ActiveSheet
For Each sht In Worksheets
loLetzteZ = sht.Cells(Rows.Count, 1).End(xlUp).Row
loLetzteS = sht.Cells(1, Columns.Count).End(xlToLeft).Column
Set rBereich = sht.Range("A2:" & Cells(loLetzteZ, loLetzteS).Address)
Application.ScreenUpdating = False
sZeile = ""
strPfad = ActiveWorkbook.Path & "\Classification" & "_" & Format(Time, "hhmmss") & ".xml"
'zeile für zeile
For Each rng In rBereich.Rows
With rng
'spalte für spalte
For I = 1 To .Columns.Count
If I = 1 Then
sZeile = sZeile & sTagO & Cells(1, I) & "=""" & .Cells(1, I) & """" & sTagC
Else
If IsEmpty(.Cells(1, I)) Then
sZeile = sZeile & sTagO & Cells(1, I) & sTagOEnd
Else
sZeile = sZeile & sTagO & Cells(1, I) & sTagC
sZeile = sZeile & .Cells(1, I)
sZeile = sZeile & sTagCStart & Cells(1, I) & sTagC
End If
End If
sZeile = sZeile & vbCrLf
Next
'sZeile = sZeile & "</" & " " & ">"
sZeile = sZeile & vbCrLf & vbCrLf
Call InDateiSchreiben(strPfad, sZeile, True)
sZeile = ""
End With
Next
Next
Application.ScreenUpdating = True
End Sub
This will traverse all worksheets. You need to use your sheet variable in the loop, instead of just setting it outside the loop
Dim oCurSheet As Worksheet
For Each oCurSheet In Me.Worksheets
oCurSheet.(Whatever you are doing with it)
Next
Edit:
I've gotten rid of rBereich in the for each collection in favor of going to the sheet. Also removed setting sht to active sheet, as the assigning is done in the for loop.
You need to use the variables in your for each loops where applicable within the loops. In the updated code you'll see sht.Cells(1,I) used to reference the current Sheet's Columns.
The additional Empty tags were due to your If IsEmpty statement, if there was nothing in the tag you were adding < (blank) </>. So I've commented the line out, if you need a value to illustrate blanks then you would want to do it simlar to the else statement, and put a value say NA where the .cells(1,I) is.
Dim sht As Worksheet
Dim loLetzteZ As Long, loLetzteS As Long, I As Long
Dim rng As Range
Dim sTagO As String, sTagC As String, sTagOEnd As String, sTagCStart As String
Dim sZeile As String
Dim strPfad As String
Dim strText As String
sTagO = "<"
sTagOEnd = "/>"
sTagC = ">"
sTagCStart = "</"
For Each sht In Me.Worksheets
loLetzteZ = sht.Cells(Rows.Count, 1).End(xlUp).Row
loLetzteS = sht.Cells(1, Columns.Count).End(xlToLeft).Column
For Each rng In sht.Range("A2:" & sht.Cells(loLetzteZ, loLetzteS).Address).Rows
Application.ScreenUpdating = False
sZeile = ""
strPfad = ActiveWorkbook.Path & "\Classification" & "_" & Format(Time, "hhmmss") & ".xml"
With rng
'spalte für spalte
For I = 1 To .Columns.Count
If I = 1 Then
sZeile = sZeile & sTagO & sht.Cells(1, I) & "=""" & .Cells(1, I) & """" & sTagC
Else
If IsEmpty(.Cells(1, I)) Then
' No Tag if empty
'sZeile = sZeile & sTagO & sht.Cells(1, I) & sTagOEnd
Else
sZeile = sZeile & sTagO & sht.Cells(1, I) & sTagC
sZeile = sZeile & .Cells(1, I)
sZeile = sZeile & sTagCStart & sht.Cells(1, I) & sTagC
End If
End If
sZeile = sZeile & vbCrLf
Next
'sZeile = sZeile & "</" & " " & ">"
sZeile = sZeile & vbCrLf & vbCrLf
'MsgBox (sZeile)
Call InDateiSchreiben(strPfad, sZeile, True)
sZeile = ""
End With
Next
Next
Application.ScreenUpdating = True
Why not using the save as XML of Excel ?
You could use use your code to reunite the data into a new sheet and then use the saveas xml format.
If you use the xml 2003 you do not need to set any xml mapping, for higher versions allow you to create your own XML mapping (see developper ruler).

R1C1 Notation To Pick Index Range for Index,Match,Match

I cannot seem to get this line of code working:
For Each errCell In BET_ws.Range("E5:E" & lastrow).Offset(0, 1 + i)
errCell.FormulaR1C1 = "=INDEX('" & cNameAndPath & BET_ws.Cells(errCell.Row,
2).Value & "'!R2C3:R1000C200,MATCH(R2C[-1],'" & cNameAndPath &
BET_ws.Cells(errCell.Row, 2).Value & "'!R2C2:R400C2,0),MATCH(RC3,'" & cNameAndPath
& BET_ws.Cells(errCell.Row, 2).Value & "'!R1C3:R1C200,0))"
Next errCell
I keep getting an object undefined error. Is it a problem with my R1C1 notation or is it an issue with BET_ws.Cells(errCell.Row,2).Value statement? In Column B the tab name needed for my INDEX reference is in the RC2 location. Not sure how to correct the issue. cNameAndPath is defined and is pulling the value I want. Another formula is running in the adjacent range with no problem.
Here is most of the code if it helps:
Sub BetConverter()
Dim wbkTarget As Workbook
Dim fNameAndPath As Variant
Dim cNameAndPath As Variant
Dim cFileName As String
Dim cFilePath As String
Dim BET_ws As Worksheet
Dim shtTarget As Worksheet
Dim ws As Worksheet
Dim lrow As Long 'last row variable
Dim lcol As Long 'last column variable
Dim lastrow As Long
Dim i As Integer
Dim cwbTarget As Workbook
Dim errCell As Range
'kill clunky processes
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
'delete summary tab if it exists
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Sheets("BET Consolidated").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'On Error GoTo Errhandler
Sheets.Add(After:=Sheets("Macro")).Name = "BET Consolidated" 'create new tab
Set BET_ws = ThisWorkbook.Sheets("BET Consolidated")
MsgBox ("Please Select the Bid Entry Tool to be Consolidated in the following File Dialog Box.")
fNameAndPath = Application.GetOpenFilename(Title:="Select Bid Entry Tool to be Consolidated")
If fNameAndPath = False Then Exit Sub
Set wbkTarget = Workbooks.Open(fNameAndPath)
MsgBox ("Please Select the MDB for Comparison in the following File Dialog Box.")
cNameAndPath = Application.GetOpenFilename(Title:="Select the MDB for Comparison")
If cNameAndPath = False Then Exit Sub
Set cwbTarget = Workbooks.Open(cNameAndPath)
cFileName = Mid$(cNameAndPath, InStrRev(cNameAndPath, "\") + 1)
cFilePath = Left$(cNameAndPath, InStrRev(cNameAndPath, "\"))
Do While shtTarget Is Nothing
For Each ws In wbkTarget.Sheets
If ws.Name Like "*H*" Then
Set shtTarget = ws
End If
Next ws
Loop
lrow = shtTarget.Cells(Rows.Count, 11).End(xlUp).Row
With shtTarget.Range("K2:K" & lrow)
BET_ws.Range("A1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
With shtTarget.Range("J2:J" & lrow)
BET_ws.Range("B1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
With shtTarget.Range("O2:O" & lrow)
BET_ws.Range("C1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
With shtTarget.Range("P2:P" & lrow)
BET_ws.Range("D1").Resize(.Rows.Count, .Columns.Count) = .Value
End With
i = 0
For Each ws In wbkTarget.Worksheets
If ws.Name Like "*H*" Then
Set shtTarget = ws
lastrow = shtTarget.Cells(shtTarget.Rows.Count, 27).End(xlUp).Row
With shtTarget.Range("AA1:AA" & lastrow)
BET_ws.Range(Range("D1").Offset(0, 1 + i).Address).Resize(.Rows.Count, .Columns.Count) = .Value
End With
For Each errCell In BET_ws.Range("E5:E" & lastrow).Offset(0, 1 + i)
errCell.FormulaR1C1 = "=INDEX('" & cNameAndPath & BET_ws.Cells(errCell.Row, 2).Value & "'!R2C3:R1000C200,MATCH(R2C[-1],'" & cNameAndPath & BET_ws.Cells(errCell.Row, 2).Value & "'!R2C2:R400C2,0),MATCH(RC3,'" & cNameAndPath & BET_ws.Cells(errCell.Row, 2).Value & "'!R1C3:R1C200,0))"
Next errCell
For Each errCell In BET_ws.Range("F5:F" & lastrow).Offset(0, 1 + i)
errCell.FormulaR1C1 = "=IF(RC[-2]=RC[-1],""MATCH"",""DOES NOT MATCH"")"
Next errCell
i = i + 3
End If
Next ws
Also tried like this:
For Each errCell In BET_ws.Range("E5:E" & lastrow).Offset(0, 1 + i)
tName = BET_ws.Cells(errCell.Row, 2).Value
errCell.FormulaR1C1 = "=INDEX('" & cFilePath & "[" & cFileName & "]" & tName & "'!R2C3:R1000C200,MATCH(R2C[-1],'" & cFilePath & "[" & cFileName & "]" & tName & "'!R2C2:R400C2,0),MATCH(RC3,'" & cFilePath & "[" & cFileName & "]" & tName & "'!R1C3:R1C200,0))"
Next errCell

Resources