Multiple CSVs to single excel VBS - vbscript

I am trying to read multiple CSVs into single spreadsheet. I got below code from google.
There are 10 CSVs present in "C:\Users\achayapa\Desktop\test". I need to have each of these CSVs in a single excel. could someone please help?
I am new to vb script.
Sub MacroLoop()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("C:\Users\achayapa\Desktop\test\*.csv")
Do While strFile <> vbNullString
ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "C:\Users\achayapa\Desktop\test\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh(BackgroundQuery:=False)
End With
strFile = Dir
Loop
End Sub

I just thought of sharing the answer to above question.
Create a VBA script as below:
Sub Macro1()
Dim strPath As String
Dim strFile As String
strPath = "C:\test\"
strFile = Dir(strPath & "*.csv")
Do While strFile <> ""
With ActiveWorkbook.Worksheets.Add
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Destination:=.Range("A1"))
.Parent.Name = Replace(strFile, ".csv", "")
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End With
strFile = Dir
Loop
End Sub
In above code include for path - '\' For example - C:\test\
After this follow include above VBA in Excel, follow steps as in below link:
http://www.ablebits.com/office-addins-blog/2013/12/06/add-run-vba-macro-excel/

Short answer: Yes it is possible.
Step 0 of long answer:
There are 2 syntactical errors in you SWub MacroLoop():
ws = Sheets.Add must be Set ws = Sheets.Add because you want to assign an object to ws.
.Refresh(BackgroundQuery:=False) must be .Refresh BackgroundQuery:=False because you must not use param list () when calling (a function/method as) a Sub (see here).
You may get problems with .TextFilePlatform and .TextFileTrailingMinusNumbers - at least I did when testing on my rather dated Excel. If so, disable those lines (' comment) and try again.
For the next step I would need a detailed account of your testing experience. What result do you expect and how did the actual outcome differ from that?

Related

How to extract data from tag or HTML class using vbscript? Only tags or classes I choose

Can someone help me? I need to extract the texts that are between tags or HTML classes using VBScript and save to a single text file. I need to save the tags or classes I define on different lines.
I've found a lot of code on the internet, but none worked as expected.
For example, I have the code below, but I can't extract classes through it, and it's not possible for more than one tag either. In many cases the code doesn't even work.
myURL = "http://rss.cnn.com/rss/edition.rss"
Set oXMLHttp = CreateObject("MSXML2.XMLHTTP")
Set ohtmlFile = CreateObject("htmlfile")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1, ForWriting = 2, ForAppending = 8
oXMLHttp.Open "GET", myURL, False
oXMLHttp.send
If oXMLHttp.Status = 200 Then
ohtmlFile.Write oXMLHttp.responseText
ohtmlFile.Close
Set oTable = ohtmlFile.getElementsByTagName("description")
sFileName = "c:\users\user\desktop\News.txt"
Set objFile = objFSO.OpenTextFile(sFileName, ForAppending, True)
For Each oTab In oTable
objFile.Write oTab.Innertext & vbCrLf
Next
objFile.Close
End If
WScript.Quit
thanks!
You could use a regular expression instead, though:
Option Explicit
Dim myURL,oXMLHttp,objFSO,Description,write2File,ws
myURL = "http://rss.cnn.com/rss/edition.rss"
set ws = CreateObject("wscript.shell")
Set oXMLHttp = CreateObject("MSXML2.XMLHTTP")
Set objFSO = CreateObject("Scripting.FileSystemObject")
oXMLHttp.Open "GET", myURL, False
oXMLHttp.send
If oXMLHttp.Status = 200 Then
Description = Extract(oXMLHttp.responseText)
Set write2File = objFSO.CreateTextFile(".\News.txt",True)
write2File.WriteLine(Description)
write2File.Close
ws.run ".\News.txt"
End If
'-------------------------------------------------------------------------
Function Extract(Data)
Dim re,Match,Matches
Set re = New RegExp
re.Global = True
re.IgnoreCase = True
re.Pattern = "<description><!\[CDATA\[([\s\S]*?)\]\]><\/description>"
Set Matches = re.Execute(Data)
For Each Match in Matches
Description = Description & Match.SubMatches(0) & vbCrlf & vbCrlf
Next
Extract = Description
End Function
'-------------------------------------------------------------------------
EDIT :
For your second request about how to get news from google :
Option Explicit
Dim myURL,oXMLHttp,objFSO,GoogleNews,write2File,ws
myURL = "https://news.google.com/?hl=en-US&gl=US&ceid=US:en"
set ws = CreateObject("wscript.shell")
Set oXMLHttp = CreateObject("MSXML2.XMLHTTP")
Set objFSO = CreateObject("Scripting.FileSystemObject")
oXMLHttp.Open "GET", myURL, False
oXMLHttp.send
If oXMLHttp.Status = 200 Then
GoogleNews = Extract(oXMLHttp.responseText)
Set write2File = objFSO.CreateTextFile(".\GoogleNews.txt",True,-1)
write2File.WriteLine(GoogleNews)
write2File.Close
ws.run ".\GoogleNews.txt"
End If
'-------------------------------------------------------------------------
Function Extract(Data)
Dim re,Match,Matches
Set re = New RegExp
re.Global = True
re.IgnoreCase = True
re.MultiLine = True
re.Pattern = "(\bclass=""DY5T1d"" >)(.+?)<\/a>"
Set Matches = re.Execute(Data)
For Each Match in Matches
GoogleNews = GoogleNews & Match.SubMatches(1) & vbCrlf & vbCrlf
Next
GoogleNews = Replace(GoogleNews,"'","'")
GoogleNews = Replace(GoogleNews,""",chr(34))
Extract = GoogleNews
End Function
'-------------------------------------------------------------------------
You are on the right track with using the getElementsByTagName Method with your ohtmlFile object. You can specify the tag types you want. For example:
Set objAnchors = ohtmlFile.getElementsByTagName("a")
This returns all <a> tags in the HTML document.

open a csv file in an active worksheet vba on mac

I am trying to rewrite my windows VBA code so i can use it on a Mac computer.
But somehow it is not possible to load the information into an active worksheet on mac.
Where MyFiles is the csv file opened by the code of http://www.rondebruin.nl/mac/mac015.html
.
I broke down the code a bit because i thought it didn't recognize the workbook. But i think the problem lies in the work book.
Set ws = ActiveWorkbook.Sheets("1. Pledges (ruw)")
MyFiles = MacScript(MyScript)
On Error GoTo 0
If MyFiles <> "" Then
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
With ws.QueryTables.Add(Connection:="TEXT;" & MyScript, Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.Refresh
End With
If ws.Range("A2").Value = vbNullString Then
ws.rows("2").EntireRow.Delete
End If
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End If
End Sub
Some how it always crashes on the .refresh even if i use the code of robin the bruijn i can't use the querytables which work perfectly on windows.
Original windows code:
Dim ws As Worksheet, strFile As String
Set ws = ActiveWorkbook.Sheets("1. Pledges (ruw)") 'set to current worksheet name
strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please selec text file...")
With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.SaveData = True
End With
If ws.Range("A2").Value = vbNullString Then
ws.rows("2").EntireRow.Delete
End If

Find and Replace?

Does anyone know of a way to do a more complex find and replace? For example, I have many documents with merge fields. I need to be able to change the merge fields in these documents based on a list of definitions\translations. So in this example lets say I have 100 equipment leases created in M$ word saved as .dot. Each one the following merge fields exists, and I want to change them all at once to a new value as shown below.
{MERGEFIELD state} -> {MERGEFIELD ownerstate}
{MERGEFIELD city} -> {MERGEFIELD ownercity}
{MERGEFIELD zip} -> {MERGEFIELD ownerzip}
It's not so important that I be able to edit more than 1 document at a time than it is that I be able to make multiple edits at once.
OK so I was able to create a solution to my own issue. To do this I created the following code to do a find and replace based on a definition list in excel.
Option Explicit
Private MyXL As Object
Sub Test()
Dim WB As Excel.Workbook, WS As Excel.Worksheet, MyDefTbl As Excel.Range, MyRow As Excel.Range
Dim MySearchRng As Excel.Range, ReplacementRng As Excel.Range
Dim myDoc As Document
Call MyInitializeOfficeApps
'Define the Workbook that contains the Definitions
Set WB = MyXL.Workbooks.Open("E:\MailMerges\Definitions\Equip.xlsx")
'Define the Woksheet that contains the Definition list
Set WS = WB.Worksheets("Sheet1")
'Define the Range name that defines the Definition list
Set MyDefTbl = WS.Range("MyDefs")
'Define the Document to be changed
Set myDoc = ActiveDocument
For Each MyRow In MyDefTbl.Rows
Set MySearchRng = WS.Cells(MyRow.Row, 1)
Set ReplacementRng = WS.Cells(MyRow.Row, 2)
'MsgBox MySearchRng & "====>" & ReplacementRng
myDoc.Select
With Selection.Find
.Text = " MERGEFIELD " & MySearchRng.Text
.Replacement.Text = " MERGEFIELD " & ReplacementRng.Text
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Next MyRow
Set MyDefTbl = Nothing
Set MyRow = Nothing
Set WS = Nothing
Set WB = Nothing
Set MyXL = Nothing
Set myDoc = Nothing
MsgBox "Complete"
End Sub
Sub MyInitializeOfficeApps()
On Error Resume Next
Set MyXL = GetObject(, "Excel.Application")
If MyXL Is Nothing Then
Set MyXL = CreateObject("Excel.Application")
End If
On Error GoTo 0
MyXL.Visible = True
End Sub

import data from web to Excel 2010 worksheet

I am trying to import data from web to Excel worksheet on win 7.
But, I do not know how to finish the left one where is marked .
Sub Ex2Macro()
Ex2 from Macro1 Macro
' Macro changed 17/07/2007 by Dr. B. I. Czaczkes
Dim qt As QueryTable
Dim temp As Variant ' Double
Set qt = ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://finance.yahoo.com/q?s=GBPUSD=X", Destination:=ActiveCell.Range("A1"))
With qt
.Name = "query1"
.BackgroundQuery = False
.SaveData = True
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "14"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.Refresh BackgroundQuery:=False
End With
With qt.ResultRange
.ClearContents
.Range("a1").Value = "USD/GBP"
.Range("b1").Value = ? ' here, what I should put so that the queried result
' is printed ?
End With
End Sub
Another piece of code that provide the exchange result.
Sub Ex3Macro()
Dim qt As QueryTable
' Dim temp As Double
Dim temp As Variant
temp = ActiveCell.Value
Set qt = Worksheets("temp").QueryTables.Add(Connection:= _
"URL;http://finance.yahoo.com/currency/convert?amt=" & _
temp & _
"&from=USD&to=GBP&submit=Convert" _
, Destination:=Worksheets("Temp").Range("a1"))
With qt
.Name = "query2"
.BackgroundQuery = False
.SaveData = True
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "13"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.Refresh BackgroundQuery:=False
End With
ActiveCell.Range("b1").Value = qt.ResultRange.Range("e3").Value
End Sub
But, no result is printed.
Any help will be appreciated.
Try selecting the Microsoft WinHTTP Services, version 5.1 reference then using this:
Sub HTTPTest()
Dim httpRequest As WinHttpRequest
Dim URL As String, strHTML As String
If httpRequest Is Nothing Then
Set httpRequest = New WinHttp.WinHttpRequest
End If
URL = "http://finance.yahoo.com/q?s=GBPUSD=X"
httpRequest.Open "GET", URL, True
httpRequest.Send
httpRequest.WaitForResponse
strHTML = httpRequest.ResponseText
Set httpRequest = Nothing
'Parse strHTML now to get your value
End Sub

Export sheet as UTF-8 CSV file (using Excel-VBA)

I would like to export a file I have created in UTF-8 CSV using VBA. From searching message boards, I have found the following code that converts a file to UTF-8 (from this thread):
Sub SaveAsUTF8()
Dim fsT, tFileToOpen, tFileToSave As String
tFileToOpen = InputBox("Enter the name and location of the file to convert" & vbCrLf & "With full path and filename ie. C:\MyFolder\ConvertMe.Txt")
tFileToSave = InputBox("Enter the name and location of the file to save" & vbCrLf & "With full path and filename ie. C:\MyFolder\SavedAsUTF8.Txt")
tFileToOpenPath = tFileToOpen
tFileToSavePath = tFileToSave
Set fsT = CreateObject("ADODB.Stream"): 'Create Stream object
fsT.Type = 2: 'Specify stream type – we want To save text/string data.
fsT.Charset = "utf-8": 'Specify charset For the source text data.
fsT.Open: 'Open the stream
fsT.LoadFromFile tFileToOpenPath: 'And write the file to the object stream
fsT.SaveToFile tFileToSavePath, 2: 'Save the data to the named path
End Sub
However, this code only converts a non-UTF-8 file to UTF-8. If I were to save my file in non-UTF-8 and then convert it to UTF-8, it would have already lost all the special characters it contained, thus rendering the process pointless!
What I'm looking to do is save an open file in UTF-8 (CSV). Is there any way of doing this with VBA?
n.b. I have also asked this question on the 'ozgrid' forum. Will close both threads together if I find a solution.
Finally in Office 2016, you can simply savs as CSV in UTF8.
Sub SaveWorkSheetAsCSV()
Dim wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim name As String
Set wsSource = ThisWorkbook.Worksheets(1)
name = "test"
Application.DisplayAlerts = False 'will overwrite existing files without asking
Set wsTemp = ThisWorkbook.Worksheets(1)
Set wbNew = ActiveWorkbook
Set wsTemp = wbNew.Worksheets(1)
wbNew.SaveAs name & ".csv", xlCSVUTF8 'new way
wbNew.Close
Application.DisplayAlerts = True
End Sub
This will save the worksheet 1 into csv named test.
Update of this code. I used this one to change all .csv files in a specified folder (labeled "Bron") and save them as csv utf-8 in another folder (labeled "doel")
Sub SaveAsUTF8()
Dim fsT As Variant, tFileToOpen As String, tFileToSave As String
Dim Message As String
Dim wb As Workbook
Dim fileName As String
Set wb = ActiveWorkbook
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Message = "Source folder incorrect"
SourceFolder = wb.Worksheets("Menu").Range("Bron") & "\"
If Dir(SourceFolder, vbDirectory) = "" Or IsEmpty(SourceFolder) Then GoTo errorhandler
Message = "Target folder incorrect"
TargetFolder = wb.Worksheets("Menu").Range("Doel") & "\"
If Dir(TargetFolder, vbDirectory) = "" Or IsEmpty(TargetFolder) Then GoTo errorhandler
fileName = Dir(SourceFolder & "\*.csv", vbNormal)
Message = "No files available."
If Len(fileName) = 0 Then GoTo errorhandler
Do Until fileName = ""
tFileToOpen = SourceFolder & fileName
tFileToSave = TargetFolder & fileName
tFileToOpenPath = tFileToOpen
tFileToSavePath = tFileToSave
Set fsT = CreateObject("ADODB.Stream"): 'Create Stream object
fsT.Type = 2: 'Specify stream type – we want To save text/string data.
fsT.Charset = "utf-8": 'Specify charset For the source text data.
fsT.Open: 'Open the stream
fsT.LoadFromFile tFileToOpenPath: 'And write the file to the object stream
fsT.SaveToFile tFileToSavePath, 2: 'Save the data to the named path
fileName = Dir()
Loop
Message = "Okay to remove all old files?"
If QuestionMessage(Message) = False Then
GoTo the_end
Else
On Error Resume Next
Kill SourceFolder & "*.csv"
On Error GoTo errorhandler
End If
the_end:
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
Exit Sub
errorhandler:
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
CriticalMessage (Message)
Exit Sub
End Sub
'----------
Function CriticalMessage(Message As String)
MsgBox Message
End Function
'----------
Function QuestionMessage(Message As String)
If MsgBox(Message, vbQuestion + vbYesNo) = vbNo Then
QuestionMessage = False
Else
QuestionMessage = True
End If
End Function
Here's my solution based on Excel VBA - export to UTF-8, which user3357963 linked to earlier. It includes macros for exporting a range and a selection.
Option Explicit
Const strDelimiter = """"
Const strDelimiterEscaped = strDelimiter & strDelimiter
Const strSeparator = ","
Const strRowEnd = vbCrLf
Const strCharset = "utf-8"
Function CsvFormatString(strRaw As String) As String
Dim boolNeedsDelimiting As Boolean
boolNeedsDelimiting = InStr(1, strRaw, strDelimiter) > 0 _
Or InStr(1, strRaw, Chr(10)) > 0 _
Or InStr(1, strRaw, strSeparator) > 0
CsvFormatString = strRaw
If boolNeedsDelimiting Then
CsvFormatString = strDelimiter & _
Replace(strRaw, strDelimiter, strDelimiterEscaped) & _
strDelimiter
End If
End Function
Function CsvFormatRow(rngRow As Range) As String
Dim arrCsvRow() As String
ReDim arrCsvRow(rngRow.Cells.Count - 1)
Dim rngCell As Range
Dim lngIndex As Long
lngIndex = 0
For Each rngCell In rngRow.Cells
arrCsvRow(lngIndex) = CsvFormatString(rngCell.Text)
lngIndex = lngIndex + 1
Next rngCell
CsvFormatRow = Join(arrCsvRow, ",") & strRowEnd
End Function
Sub CsvExportRange( _
rngRange As Range, _
Optional strFileName As Variant _
)
Dim rngRow As Range
Dim objStream As Object
If IsMissing(strFileName) Or IsEmpty(strFileName) Then
strFileName = Application.GetSaveAsFilename( _
InitialFileName:=ActiveWorkbook.Path & "\" & rngRange.Worksheet.Name & ".csv", _
FileFilter:="CSV (*.csv), *.csv", _
Title:="Export CSV")
End If
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 2
objStream.Charset = strCharset
objStream.Open
For Each rngRow In rngRange.Rows
objStream.WriteText CsvFormatRow(rngRow)
Next rngRow
objStream.SaveToFile strFileName, 2
objStream.Close
End Sub
Sub CsvExportSelection()
CsvExportRange ActiveWindow.Selection
End Sub
Sub CsvExportSheet(varSheetIndex As Variant)
Dim wksSheet As Worksheet
Set wksSheet = Sheets(varSheetIndex)
CsvExportRange wksSheet.UsedRange
End Sub

Resources