Need to convert excel data into XML format.
'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
Kindly let me how to do this in VBA or provide a link where I can refer. Thanks in Advance.
For a simple case one way would be to build the xml line by line
Sub vba_code_to_convert_excel_to_xml2()
Const FOLDER = "C:\temp\"
Const XLS_FILE = "testwb.xlsx"
Const XML_FILE = "testX.xml"
Const XML = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf & _
"<Core-Information ContextID=""Context1"" WorkspaceID=""Main"">" & vbCrLf & _
" <UserList>" & vbCrLf
Dim wb As Workbook, ws As Worksheet, ar, s As String
Dim iLastRow As Long, r As Long, n As Integer
' open source workbook
Set wb = Workbooks.Open(FOLDER & XLS_FILE, 1, 1)
Set ws = wb.Sheets("Sheet1")
iLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
' create XML document
'<User ID="Aravind" ForceAuthentication="false" Password="1234" EMail="Aravind#gmail.com">
' <Name>Aravind</Name>
' <UserGroupLink UserGroupID="Sports"/>
'</User>
s = XML
For r = 2 To iLastRow
s = s & " <User ID=""" & ws.Cells(r, 1) & """" & _
" ForceAuthentication=""false"" Password=""" & ws.Cells(r, 2) & """" & _
" EMail=""" & ws.Cells(r, 3) & """>" & vbCrLf
s = s & " <Name>" & ws.Cells(r, 1) & "</Name>" & vbCrLf
ar = Split(ws.Cells(r, 4), ",")
For n = LBound(ar) To UBound(ar)
s = s & " <UserGroupLink UserGroupID=""" & Trim(ar(n)) & """/>" & vbCrLf
Next
s = s & " </User>" & vbCrLf
Next
s = s & " </UserList>" & vbCrLf & "</Core-Information>"
' save
Dim fso, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.createtextfile(FOLDER & XML_FILE)
ts.write s
ts.Close
MsgBox "Xml created to " & FOLDER & XML_FILE
End Sub
I have a macro in an Excel Workbook, that is connected to a button that says Export
When I click the button, it triggers the Export XML dialog and I have to manually search for a folder to export it into and enter the filename.
Since the folders in my Documents are named exactly the same as the value of the Cell A24, i would like it to direct itself into the correct folder and suggest me a filename based on the value of the Cell A24 with some extra text behind it.
So far i have this in the VBA:
Public Sub ExportToXML()
Dim strFilePath As String
Dim POFilePath As String
Dim FOFilePath As String
Dim POFileName As String
Dim FOFileName As String
Dim XMLDoc As MSXML2.DOMDocument
Dim xNode As MSXML2.IXMLDOMNode
Dim xAttribute As MSXML2.IXMLDOMAttribute
Dim xElement As MSXML2.IXMLDOMElement
Dim xElementRoot As MSXML2.IXMLDOMElement
Application.ScreenUpdating = False
MainSheetName = ActiveSheet.Name
POFilePath = "C:\Users\admin\Desktop\" & Range("A24")
FOFilePath = "C:\Users\admin\Desktop\" & Range("D22") & " " & Range("A22")
POFileName = "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
FOFileName = "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
If Range("A24").value = "0" Then
strFilePath = Application.GetSaveAsFilename(FOFilePath & FOFileName, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
Else
strFilePath = Application.GetSaveAsFilename(POFilePath & POFileName, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
End If
If strFilePath = "False" Then Exit Sub
This gives me the right filename suggestion, but it doesn't direct me to the folder and goes to Desktop.
Any help would be appriciated!
EDIT:
I tried merging the Strings together a bit more and came up with this:
Public Sub ExportToXML()
Dim strFilePath As String
Dim POFilePath As String
Dim FOFilePath As String
Dim XMLDoc As MSXML2.DOMDocument
Dim xNode As MSXML2.IXMLDOMNode
Dim xAttribute As MSXML2.IXMLDOMAttribute
Dim xElement As MSXML2.IXMLDOMElement
Dim xElementRoot As MSXML2.IXMLDOMElement
Application.ScreenUpdating = False
MainSheetName = ActiveSheet.Name
POFilePath = "C:\Users\admin\Desktop\" & Range("A24") & Range("A24").value & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
FOFilePath = "C:\Users\admin\Desktop\" & Range("D22") & " " & Range("A22") & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
If Range("A24").value = "0" Then
strFilePath = Application.GetSaveAsFilename(FOFilePath, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
Else
strFilePath = Application.GetSaveAsFilename(POFilePath, fileFilter:="XML files (*.xml),*.xml", Title:="Save FileAs...")
End If
If strFilePath = "False" Then Exit Sub
The problem is, that VBA thinks that in:
POFilePath = "C:\Users\admin\Desktop\" & Range("A24") & Range("A24").value & "_report " & Range("D13").value & " " & Range("F13").value & ".xml"
the first Range("A24") belongs to the filename part and doesn't continue on with the filepath. So if the value in A24 was "test", then this suggests saving the xml to Desktop with the filename testttest_report 11 2020
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
I have used hyperlinks.add several times now and never had any problems with it.
Now I added a line of code: SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName to my base code (which you can find under here). This should add a link to the newly created document.
The problem is that excel always says it cannot open the file. The link I enter via code is right, as I copied it with debug.print and it opened the file without a problem.
It came to my attention that the hyperlink I added was modified by excel when I hold my mouse over the hyperlink. I wonder how this is possible.
A second problem I encounterd is that when I enter the hyperlink manually and navigate manually to the file to make sure it takes the right file, excel still modifies my link and says "cannot open specified file".
Anyone an idea what might go wrong here? Thanks!
Code:
`Application.ScreenUpdating = False
Dim i, j, FSO As Object, SV, ESN, PartName, ToPath, FromPath, NewName, MsgBoxAnswer, TargetBook As Workbook, SourceBook As Workbook
Dim OS, PN, SN, ProjectNumber, Customer, StartDate, EndDate, LastRowCMM
ESN = ActiveWorkbook.ActiveSheet.Range("G2").Value
SV = ActiveWorkbook.ActiveSheet.Range("K2").Value
ProjectNumber = ActiveWorkbook.ActiveSheet.Range("A3").Value
Customer = ActiveWorkbook.ActiveSheet.Range("G3").Value
Set FSO = CreateObject("scripting.filesystemobject")
PGB.Min = 0
PGB.Value = 0
PGB.Max = 22
'Create main folder
If SV <> 1 Then
SV = "(SV " & SV & ")"
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN
End If
If FSO.folderexists(ToPath) = True Then
MsgBoxAnswer = MsgBox("Folder already created.", vbExclamation, "Folder exists.")
Exit Sub
End If
FSO.createfolder (ToPath)
'Create all Excel files & fill them in
For i = 6 To 27
FromPath = "U:\tmo\VANMOLLE\Fiches constat\Template fiches constat LEAP.xlsm"
If SV <> 1 Then
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\"
Else
ToPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\"
End If
FSO.copyfile Source:=FromPath, Destination:=ToPath
NewName = "#" & ESN & "_" & ActiveWorkbook.ActiveSheet.Range("A" & i) & ".xlsm"
If SV <> 1 Then
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & " " & SV & "\Template fiches constat LEAP.xlsm"
Else
FromPath = "U:\tmo\vanmolle\fiches constat\Fiches constats #" & ESN & "\Template fiches constat LEAP.xlsm"
End If
Name FromPath As ToPath & NewName
Set SourceBook = ThisWorkbook
Set TargetBook = Workbooks.Open(ToPath & NewName)
TargetBook.Sheets("Sheet1").Activate
PartName = SourceBook.ActiveSheet.Range("A" & i).Value
OS = SourceBook.ActiveSheet.Range("D" & i).Value
PN = SourceBook.ActiveSheet.Range("B" & i).Value
SN = SourceBook.ActiveSheet.Range("C" & i).Value
If SN = "" Then SN = "N/A"
StartDate = SourceBook.ActiveSheet.Range("G" & i).Value
EndDate = SourceBook.ActiveSheet.Range("H" & i).Value
'check for right CMM
'LastRowCMM = TargetBook.Sheets("Révision CMM").Range("B6").End(xlDown).Row
'For j = 1 To LastRowCMM
'If PartName = TargetBook.Sheets("Révision CMM").Range("A" & j).Value Then ActiveWorkbook.ActiveSheet.Range("A23").Value = ActiveWorkbook.Sheets("Révision CMM").Range("B" & j).Value
'Next j
TargetBook.ActiveSheet.Range("B9").Value = PartName
TargetBook.ActiveSheet.Range("B10").Value = OS
TargetBook.ActiveSheet.Range("B11").Value = "# " & ESN
TargetBook.ActiveSheet.Range("B12").Value = PN
TargetBook.ActiveSheet.Range("B13").Value = SN
TargetBook.ActiveSheet.Range("E9").Value = StartDate
TargetBook.ActiveSheet.Range("E10").Value = EndDate
TargetBook.ActiveSheet.Range("B14").Value = ProjectNumber
TargetBook.ActiveSheet.Range("B15").Value = Customer
TargetBook.ActiveSheet.PageSetup.PrintArea = "$A$1:$E$39"
TargetBook.Close True
'Add hyperlink
SourceBook.Sheets(ESN & "_SV" & SV).Hyperlinks.Add Anchor:=Range("A" & i), _
Address:=ToPath & NewName
Application.Wait (Now + TimeValue("00:00:01"))
Progress.PGB.Value = i - 5
Progress.Lbl.Caption = "File " & i - 5 & " of 22 copied."
Next i
Application.ScreenUpdating = True`
First thing first - declare each variable explicitly. E.g.:
Dim i as Long, j as Long, FSO As Object, SV as String, ESN as String and etc.
The way in your code - Dim i, j, SV, ESN, PartName, ToPath they are declared as variant.
Second thing second - try something really very small to debug further. E.g. write this small piece:
Sub TestMe()
With Worksheets(1)
.Hyperlinks.Add anchor:=.Range("A1"), Address:="C:\Users\UserName\Desktop\test.docx"
End With
End Sub
and check whether it works. If it doesn't, debug further, check whether cells are locked or anything similar.
Im sorry about the large amount of code but I've been looking over a number of days now to try and resolve this problem. Basically this code runs in outlook when I start it up. It exports different types of emails from different inbox's where different subject headers exist.
It collects parts of the subject heading and parts of the email body and exports this as text into my excel spreadsheet.
The problem I have is that this code actually works fine, and it use to open an excel spreadsheet in the background and export the information into a new row in the relevant columns. Once it has done this it would automatically save the spreadsheet and close.
Now however for some reason, it will do all of that but will not close the spreadsheet and Excel shows up as a running service in windows task manager. This should not be the case and the spreadsheet should save changes and close automatically.
'On the next line edit the path to the spreadsheet you want to export to
Const WORKBOOK_PATH = "X:\New_Supplier_Set_Ups_&_Audits\Supplier SetUps & Amendments.xls"
'On the next line edit the name of the sheet you want to export to
Const SHEET_NAME = "Validations"
Const SHEET_NAME2 = "BankSetup"
Const SHEET_NAME3 = "CreditChecks"
Const SHEET_NAME4 = "Statistics"
Const MACRO_NAME = "Export Messages to Excel (Rev 7)"
Const xlContinuous As Integer = 1
Const vbBlack As Integer = 0
Const xlThin As Integer = 2
Dim olkMsg As Object, _
olkMsg2 As Object, _
excApp As Object, _
excWkb As Object, _
excWks As Object, _
excWks2 As Object, _
excWks3 As Object, _
excWks4 As Object, _
intRow As Integer, _
intRow2 As Integer, _
intRow3 As Integer, _
intRow4 As Integer, _
intExp As Integer, _
intVersion As Integer
intVersion = GetOutlookVersion()
Set excApp = CreateObject("Excel.Application")
Set excWkb = excApp.Workbooks.Open(WORKBOOK_PATH)
Set excWks = excWkb.Worksheets(SHEET_NAME)
Set excWks2 = excWkb.Worksheets(SHEET_NAME2)
Set excWks3 = excWkb.Worksheets(SHEET_NAME3)
Set excWks4 = excWkb.Worksheets(SHEET_NAME4)
intRow = excWks.UsedRange.Rows.Count + 1
intRow2 = excWks2.UsedRange.Rows.Count + 1
intRow3 = excWks3.UsedRange.Rows.Count + 1
intRow4 = excWks4.UsedRange.Rows.Count + 1
'Write messages to spreadsheet
Dim ns As Outlook.NameSpace
Dim Items As Outlook.Items
Dim Items2 As Outlook.Items
Dim objAttachments As Outlook.Attachments
Dim objMsg As Outlook.MailItem 'Object
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
Dim withParts As String
Dim withoutParts As String
' Get the MAPI Namespace
Set ns = Application.GetNamespace("MAPI")
' Get the Items for the Inbox in the specified account
Set Items = ns.Folders("New Suppliers").Folders("Inbox").Items
Set Items2 = ns.Folders("Credit Checks").Folders("Inbox").Items
' Start looping through the items
For Each olkMsg In Items
'Only export messages, not receipts or appointment requests, etc.
If olkMsg.UnRead = True Then
If olkMsg.class = olMail Then
If olkMsg.Subject Like "Accept: (Update) New Supplier Request*" Or olkMsg.Subject Like "Accept: (Approval Required) - New Supplier Request*" Or olkMsg.Subject Like "Reject: (Approval Required) - New Supplier Request*" Or olkMsg.Subject Like "Accept: (IMPORTANT REMINDER!) - New Supplier Request*" Then
'Add a row for each field in the message you want to export
excWks.Cells(intRow, 1) = olkMsg.ReceivedTime
Dim LResult As String
LResult = Replace(GetSMTPAddress(olkMsg, intVersion), ".", " ")
LResult = Left(LResult, InStrRev(LResult, "#") - 1)
excWks.Cells(intRow, 2) = LResult
excWks.Cells(intRow, 3) = olkMsg.VotingResponse
Dim s As String
s = olkMsg.Subject
Dim indexOfName As Integer
indexOfName = InStr(1, s, "Reference: ")
Dim finalString As String
finalString = Right(s, Len(s) - indexOfName - 10)
excWks.Cells(intRow, 4) = finalString
intRow = intRow + 1
olkMsg.UnRead = False
End If
End If
If olkMsg.class = olMail Then
If olkMsg.Subject Like "Complete: Bank Details Set-Up for New Supplier*" Or olkMsg.Subject Like "Incomplete: Bank Details Set-Up for New Supplier*" Then
'Add a row for each field in the message you want to export
excWks2.Cells(intRow2, 1) = olkMsg.ReceivedTime
Dim LResult2 As String
LResult2 = Replace(GetSMTPAddress(olkMsg, intVersion), ".", " ")
LResult2 = Left(LResult2, InStrRev(LResult2, "#") - 1)
excWks2.Cells(intRow2, 2) = LResult2
excWks2.Cells(intRow2, 3) = olkMsg.VotingResponse
Dim s2 As String
s2 = olkMsg.Subject
Dim indexOfName2 As Integer
indexOfName2 = InStr(1, s2, "Reference: ")
Dim finalString2 As String
finalString2 = Right(s2, Len(s2) - indexOfName2 - 10)
excWks2.Cells(intRow2, 4) = finalString2
intRow2 = intRow2 + 1
olkMsg.UnRead = False
End If
End If
If olkMsg.class = olMail Then
If olkMsg.Subject Like "New Supplier Request - Reference:*" Then
'Add a row for each field in the message you want to export
Dim FSO As Object
Dim FolderPath As String
Set FSO = CreateObject("scripting.filesystemobject")
Dim b4 As String
Dim strNewFolderName As String
If TypeName(olkMsg) = "MailItem" Then
b4 = olkMsg.Body
Dim indexOfNameb As Integer
indexOfNameb = InStr(UCase(b4), UCase("Company name: "))
Dim indexOfNamec As Integer
indexOfNamec = InStr(UCase(b4), UCase("Company number: "))
Dim finalStringb As String
finalStringb = Mid(b4, indexOfNameb, indexOfNamec - indexOfNameb)
LResult336 = Replace(finalStringb, "Company Name: ", "")
Dim LResult21 As String
Dim LResult211 As String
Dim LResult2113 As String
LResult21 = Trim(LResult336)
LResult211 = Replace(LResult21, Chr(10), "")
LResult2113 = Replace(LResult211, Chr(13), "")
excWks4.Cells(intRow4, 2) = Trim(LResult2113)
FolderPath = "\\uksh000-file06\purchasing\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Trim(LResult2113)
If FSO.FolderExists(FolderPath) = False Then
Dim strDir As String
strDir = "\\uksh000-file06\purchasing\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Trim(LResult2113)
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir
FileCopy "X:\New_Supplier_Set_Ups_&_Audits\assets\audit.xls", "X:\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Trim(LResult2113) & "\audit.xls"
Else
MsgBox "Directory exists."
End If
Else
End If
End If
Dim b5 As String
If TypeName(olkMsg) = "MailItem" Then
b5 = olkMsg.Body
Dim indexOfNameb2 As Integer
indexOfNameb2 = InStr(UCase(b5), UCase("Company Number: "))
Dim indexOfNamec2 As Integer
indexOfNamec2 = InStr(UCase(b5), UCase("VAT Number: "))
Dim finalStringb2 As String
finalStringb2 = Mid(b5, indexOfNameb2, indexOfNamec2 - indexOfNameb2)
LResult3362 = Replace(finalStringb2, "Company Number: ", "")
excWks4.Cells(intRow4, 3) = LResult3362
End If
Dim b6 As String
If TypeName(olkMsg) = "MailItem" Then
b6 = olkMsg.Body
Dim indexOfNameb3 As Integer
indexOfNameb3 = InStr(UCase(b6), UCase("VAT Number: "))
Dim indexOfNamec3 As Integer
indexOfNamec3 = InStr(UCase(b6), UCase("Contact Name: "))
Dim finalStringb3 As String
finalStringb3 = Mid(b6, indexOfNameb3, indexOfNamec3 - indexOfNameb3)
LResult3363 = Replace(finalStringb3, "VAT Number: ", "")
excWks4.Cells(intRow4, 4) = LResult3363
End If
Dim l As String
excWks4.Cells(intRow4, 5) = Trim(excWks4.Cells(intRow4, 5))
l = excWks4.Cells(intRow4, 5).Address
excWks4.Cells(intRow4, 6).FormulaArray = "=IF(ISERROR(INDEX('Up'!$A$1:$G$10004,SMALL(IF(LEFT('Up'!$B$1:$B$10004,5)=LEFT(" & l & ",5),ROW($B$1:$B$10004)),ROW(1:1)),6)),""ZZZ"",INDEX('Up'!$A$1:$G$10004,SMALL(IF(LEFT('Up'!$B$1:$B$10004,5)=LEFT(" & l & ",5),ROW($B$1:$B$10004)),ROW(1:1)),6))"
Dim b7 As String
If TypeName(olkMsg) = "MailItem" Then
b7 = olkMsg.Body
Dim indexOfNameb4 As Integer
indexOfNameb4 = InStr(UCase(b7), UCase("Description of the provisional Supplier:"))
Dim indexOfNamec4 As Integer
indexOfNamec4 = InStr(UCase(b7), UCase("Current Status: "))
Dim finalStringb4 As String
Dim LResult3364 As String
Dim LResult33644 As String
Dim LResult336445 As String
finalStringb4 = Mid(b7, indexOfNameb4, indexOfNamec4 - indexOfNameb4)
LResult3364 = Replace(finalStringb4, "Description of the provisional Supplier:", "")
LResult33644 = Replace(LResult3364, Chr(10), "")
LResult336445 = Replace(LResult33644, Chr(13), "")
Dim TrimString As String
TrimString = Trim(LResult336445)
excWks4.Cells(intRow4, 5) = Trim(TrimString)
End If
Dim b77 As String
If TypeName(olkMsg) = "MailItem" Then
b77 = olkMsg.Body
Dim indexOfNameb47 As Integer
indexOfNameb47 = InStr(UCase(b77), UCase("Contact Number: "))
Dim indexOfNamec47 As Integer
indexOfNamec47 = InStr(UCase(b77), UCase("Contact Email: "))
Dim finalStringb47 As String
Dim LResult33647 As String
Dim LResult336447 As String
Dim LResult3364457 As String
finalStringb47 = Mid(b77, indexOfNameb47, indexOfNamec47 - indexOfNameb47)
LResult33647 = Replace(finalStringb47, "Contact Number: ", "")
LResult336447 = Replace(LResult33647, Chr(10), "")
LResult3364457 = Replace(LResult336447, Chr(13), "")
Dim TrimString7 As String
TrimString7 = Trim(LResult3364457)
excWks4.Cells(intRow4, 11) = Trim(TrimString7)
End If
Dim b777 As String
If TypeName(olkMsg) = "MailItem" Then
b777 = olkMsg.Body
Dim indexOfNameb477 As Integer
indexOfNameb477 = InStr(UCase(b777), UCase("Contact Email: "))
Dim indexOfNamec477 As Integer
indexOfNamec477 = InStr(UCase(b777), UCase("Case Reference: "))
Dim finalStringb477 As String
Dim LResult336477 As String
Dim LResult3364477 As String
Dim LResult33644577 As String
finalStringb477 = Mid(b777, indexOfNameb477, indexOfNamec477 - indexOfNameb477)
LResult336477 = Replace(finalStringb477, "Contact Email: ", "")
LResult3364477 = Replace(LResult336477, Chr(10), "")
LResult33644577 = Replace(LResult3364477, Chr(13), "")
Dim TrimString77 As String
TrimString77 = Trim(LResult33644577)
excWks4.Cells(intRow4, 12) = Trim(TrimString77)
End If
Dim b7777 As String
If TypeName(olkMsg) = "MailItem" Then
b7777 = olkMsg.Body
Dim indexOfNameb4777 As Integer
indexOfNameb4777 = InStr(UCase(b7777), UCase("Requested Payment Term: "))
Dim indexOfNamec4777 As Integer
indexOfNamec4777 = InStr(UCase(b7777), UCase("Description of the provisional Supplier: "))
Dim finalStringb4777 As String
Dim LResult3364777 As String
Dim LResult33644777 As String
Dim LResult336445777 As String
finalStringb4777 = Mid(b7777, indexOfNameb4777, indexOfNamec4777 - indexOfNameb4777)
LResult3364777 = Replace(finalStringb4777, "Requested Payment Term: ", "")
LResult33644777 = Replace(LResult3364777, Chr(10), "")
LResult336445777 = Replace(LResult33644777, Chr(13), "")
Dim TrimString777 As String
TrimString777 = Trim(LResult336445777)
excWks4.Cells(intRow4, 29) = TrimString777
End If
Dim s4 As String
s4 = olkMsg.Subject
Dim indexOfName4 As Integer
indexOfName4 = InStr(1, s4, "Reference: ")
Dim finalString4 As String
finalString4 = Right(s4, Len(s4) - indexOfName2 - 34)
excWks4.Cells(intRow4, 7) = finalString4
excWks4.Cells(intRow4, 9) = "Pending"
excWks4.Cells(intRow4, 10).Formula = "=IF(" & excWks4.Cells(intRow4, 25).Address & "=""Declined"",""Manager has Declined"",IF(" & excWks4.Cells(intRow4, 25).Address & "<>""Yes"",IFERROR(CONCATENATE(""Manager has "" & INDEX(Validations!$C$1:$C$9958,MATCH(" & excWks4.Cells(intRow4, 7).Address & ",Validations!$D$1:$D$9958,0))),IF((TODAY()-" & excWks4.Cells(intRow4, 13).Address & ")>=5,""Approval Is Overdue"",""Approval Is Pending"")),IFERROR(CONCATENATE(""Manager has "" & INDEX(Validations!$C$1:$C$9958,MATCH(" & excWks4.Cells(intRow4, 7).Address & ",Validations!$D$1:$D$9958))),""Approval Overidden"")))"
excWks4.Cells(intRow4, 15) = "Pending"
excWks4.Cells(intRow4, 13) = olkMsg.ReceivedTime
Dim LResult33 As String
LResult33 = Replace(GetSMTPAddress(olkMsg, intVersion), ".", " ")
LResult33 = Left(LResult33, InStrRev(LResult33, "#") - 1)
excWks4.Cells(intRow4, 17) = LResult33
excWks4.Cells(intRow4, 18) = "=IFERROR(INDEX('Depot Data'!$F$1:$F$10004,MATCH(" & excWks4.Cells(intRow4, 17).Address & ",'Depot Data'!$E$1:$E$10004,0)),"""")"
excWks4.Cells(intRow4, 19) = "=IFERROR(INDEX('Depot Data'!$H$1:$H$10004,MATCH(" & excWks4.Cells(intRow4, 17).Address & ",'Depot Data'!$E$1:$E$10004,0)),"""")"
excWks4.Cells(intRow4, 20) = "Yes"
excWks4.Cells(intRow4, 23) = "Attach"
excWks4.Cells(intRow4, 24) = "Audit"
excWks4.Cells(intRow4, 25).Formula = "No"
excWks4.Cells(intRow4, 27) = "=Username()"
excWks4.Cells(intRow4, 28) = "Pending"
excWks4.Cells(intRow4, 31) = "V0000847"
excWks4.Cells(intRow4, 32) = "Action"
excWks4.Cells(intRow4, 33) = 1
excWks4.Cells(intRow4, 33).Interior.ColorIndex = 35
Dim LResult21234 As String
LResult21234 = GetSMTPAddress(olkMsg, intVersion)
excWks4.Cells(intRow4, 34) = "=HYPERLINK(""\\UKSH000-FILE06\Purchasing\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Trim(LResult2113) & "\log.txt"",""Log"")"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("\\UKSH000-FILE06\Purchasing\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Trim(LResult2113) & "\log.txt", True)
a.WriteLine ("Log for Supplier: " & Trim(LResult2113) & " (Created: " & Date & ")")
a.WriteLine (Date & " - " & Time & " - Request received in NewSuppliers#Hewden.co.uk by " & LResult21234 & ", and added to New Supplier Database")
a.Close
Dim Rng As Object
Set Rng = excWks4.Range("B" & intRow4 & ":AH" & intRow4 & "")
With Rng.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
excWks4.Range("B" & intRow4 & ":AH" & intRow4 & "").WrapText = False
intRow4 = intRow4 + 1
olkMsg.UnRead = False
If IsNumeric(LResult3362) Then
TempFilePath = "\\UKSH000-File06\Purchasing\New_Supplier_Set_Ups_&_Audits\assets\"
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "<p style='color:#000;font-family:calibri;font-size:16'>" & "Dear New Accounts, " & vbNewLine & vbNewLine & _
"<br><B>F.A.O: Beth Crowe </b>" & vbNewLine & vbNewLine & _
"<br><br>" & "This is an automated email sent to you from New Suppliers. This is a credit refrence request." & vbNewLine & vbNewLine & _
"<br>" & "Please would you be able to perform a credit check on the following new supplier:" & vbNewLine & vbNewLine & _
"<br><br><br>" & "Company Name: " & "<b>" & Trim(LResult2113) & "</b>" & vbNewLine & vbNewLine & _
"<br>" & "Company Number: " & "<b>" & Trim(LResult3362) & "</b>" & vbNewLine & vbNewLine & _
"<br>" & "Case Reference Number (Purchasing Use Only): " & "<b>" & finalString4 & "</b>" & vbNewLine & vbNewLine & _
"<br><br><br>" & "In the event that you have any enquiries, please keep a note of the case reference number. For any questions please contact NewSuppliers#Hewden.co.uk." & vbNewLine & vbNewLine & _
"<br><br>" & "Kind Regards," & "</font></p>" & vbNewLine & _
"<p style='color:#000;font-family:calibri;font-size:18'><b>Hewden Supply Chain Department</b></font></p>" & vbNewLine & _
"<br><br><img src='cid:cover.jpg'" & "width='800' height='64'><br>" & vbNewLine & _
"<img src='cid:subs.jpg'" & "width='274' height='51'>"
With OutMail
.SentOnBehalfOfName = "newsuppliers#hewden.co.uk"
.To = "mark.o'brien#hewden.co.uk"
.CC = ""
.BCC = ""
.Subject = "(Credit Reference) New Supplier Credit Check - Reference: " & finalString4
.Attachments.Add TempFilePath & "cover.jpg", olByValue, 0
.Attachments.Add TempFilePath & "subs.jpg", olByValue, 0
.HtmlBody = strbody
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
Else
Dim b9 As String
If TypeName(olkMsg) = "MailItem" Then
b9 = olkMsg.Body
Dim indexOfName9 As Integer
indexOfName9 = InStr(UCase(b9), UCase("Full Name of Tradesman: "))
Dim indexOfNam9 As Integer
indexOfNam9 = InStr(UCase(b9), UCase("D.O.B of Tradesman: "))
Dim finalString9 As String
finalString9 = Mid(b9, indexOfName9, indexOfNam9 - indexOfName9)
LResult3369 = Replace(finalString9, "Full Name of Tradesman: ", "")
End If
Dim b10 As String
If TypeName(olkMsg) = "MailItem" Then
b10 = olkMsg.Body
Dim indexOfName99 As Integer
indexOfName99 = InStr(UCase(b10), UCase("D.O.B of Tradesman: "))
Dim indexOfNam99 As Integer
indexOfNam99 = InStr(UCase(b10), UCase("Address of Tradesman: "))
Dim finalString99 As String
finalString99 = Mid(b10, indexOfName99, indexOfNam99 - indexOfName99)
LResult33699 = Replace(finalString99, "D.O.B of Tradesman: ", "")
End If
Dim b101 As String
If TypeName(olkMsg) = "MailItem" Then
b101 = olkMsg.Body
Dim indexOfName991 As Integer
indexOfName991 = InStr(UCase(b101), UCase("Address of Tradesman: "))
Dim indexOfNam991 As Integer
indexOfNam991 = InStr(UCase(b101), UCase("VAT Number: "))
Dim finalString991 As String
finalString991 = Mid(b101, indexOfName991, indexOfNam991 - indexOfName991)
LResult336991 = Replace(finalString991, "Address of Tradesman: ", "")
End If
TempFilePath = "\\UKSH000-File06\Purchasing\New_Supplier_Set_Ups_&_Audits\assets\"
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "<p style='color:#000;font-family:calibri;font-size:16'>" & "Dear New Accounts, " & vbNewLine & vbNewLine & _
"<br><B>F.A.O: Beth Crowe </b>" & vbNewLine & vbNewLine & _
"<br><br>" & "This is an automated email sent to you from New Suppliers. This is a credit refrence request." & vbNewLine & vbNewLine & _
"<br>" & "Please would you be able to perform a credit check on the following new supplier:" & vbNewLine & vbNewLine & _
"<br><br><br>" & "Trading Name: " & "<b>" & Trim(LResult2113) & "</b>" & vbNewLine & vbNewLine & _
"<br>" & "Full Name of Tradesman: " & "<b>" & LResult3369 & "</b>" & vbNewLine & vbNewLine & _
"<br>" & "Tradesman Date of Birth: " & "<b>" & LResult33699 & "</b>" & vbNewLine & vbNewLine & _
"<br>" & "Tradesman Address: " & "<b>" & LResult336991 & "</b>" & vbNewLine & vbNewLine & _
"<br><br>" & "Case Reference Number (Purchasing Use Only): " & "<b>" & finalString4 & "</b>" & vbNewLine & vbNewLine & _
"<br><br><br>" & "In the event that you have any enquiries, please keep a note of the case reference number. For any questions please contact NewSuppliers#Hewden.co.uk." & vbNewLine & vbNewLine & _
"<br><br>" & "Kind Regards," & "</font></p>" & vbNewLine & _
"<p style='color:#000;font-family:calibri;font-size:18'><b>Hewden Supply Chain Department</b></font></p>" & vbNewLine & _
"<br><br><img src='cid:cover.jpg'" & "width='800' height='64'><br>" & vbNewLine & _
"<img src='cid:subs.jpg'" & "width='274' height='51'>"
With OutMail
.SentOnBehalfOfName = "newsuppliers#hewden.co.uk"
.To = "mark.o'brien#hewden.co.uk"
.CC = ""
.BCC = ""
.Subject = "(Credit Reference) New Supplier Credit Check - Reference: " & finalString4
.Attachments.Add TempFilePath & "cover.jpg", olByValue, 0
.Attachments.Add TempFilePath & "subs.jpg", olByValue, 0
.HtmlBody = strbody
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
End If
End If
End If
End If
Next
I dont see save and close lines in your code. Try something like:
excWks4.Save
excWks4.Close
You may need to declare excWks4 like Workbook istead of Object.
Dim excWks4 as Workbook