Graphs with various Y values and one X values in Excel VBA - excel

This is the code i use to create a graph which searches for .csv {created using excel application} file in the path specified. It plots the column 'B' { Y axis } against column 'C' {X-axis}.. I want to one more column 'A' to my Y axis keeping column 'C' as the X axis.. How can i do that???
here is the code...
Sub Draw_Graph()
Dim strPath As String
Dim strFile As String
Dim strChart As String
Dim i As Integer
Dim j As Integer
strPath = "C:\PortableRvR\report\"
strFile = Dir(strPath & "*.csv")
i = 1
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
Files(i) = .Parent.Name
i = i + 1
End With
End With
strFile = Dir
Loop
numOfFiles = i - 1
chartName = "Chart 1"
For j = 1 To numOfFiles
strFile = Files(j)
Sheets(strFile).Select
Plot_y = Range("B1", Selection.End(xlDown)).Rows.Count
Plot_x = Range("C1", Selection.End(xlDown)).Rows.Count
Sheets("GraphDisplay").Select
If j = 1 Then ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(j).Name = strFile
ActiveChart.SeriesCollection(j).XValues = Sheets(strFile).Range("C1:C" & Plot_x)
ActiveChart.SeriesCollection(j).Values = Sheets(strFile).Range("B1:B" & Plot_y)
ActiveChart.SeriesCollection(j).MarkerStyle = -4142
ActiveChart.SeriesCollection(j).Smooth = False
Next j
ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.Axes(xlValue).DisplayUnit = xlMillions
ActiveChart.Axes(xlValue).HasDisplayUnitLabel = False
End Sub

you can add 2 series for every file (j and j+1 inside for j = 1 to 2*numOfFiles step 2) and repeat everything for j+1 series except:
ActiveChart.SeriesCollection(j).Values = Sheets(strFile).Range("A1:A" & Plot_y)
ActiveChart.SeriesCollection(j+1).Values = Sheets(strFile).Range("B1:B" & Plot_y)

Not for points
I was planning to post this as a comment (and hence do not select this as an answer. All credit to #Aprillion) but the comment would not have formatted the code as this post would have done.
Whenever you add a series as Aprillion mentioned you have to also add one more line. I just tested this with small piece of data and it works.
'<~~ You have to call this everytime you add a new series
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Values = "=Sheet1!$B$1:$B$6"
'<~~ You have to call this everytime you add a new series
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).Values = "=Sheet1!$A$1:$A$6"
Also since there is a huge difference between your Series 1 Data and Series 2 data (as per the snapshot), the 2nd series will be very close to X Axis.
Hope this is what you wanted?
FOLLOWUP
Is this what you are trying?
Dim files(1 To 20) As String
Dim numOfFiles As Integer
Dim chartName As String, shName as String
Sub Time_Graph()
Dim strPath As String, strFile As String, strChart As String
Dim i As Long, j As Long, n As Long
strPath = "C:\PortableRvR\report\"
strFile = Dir(strPath & "*.csv")
i = 1
Do While strFile <> ""
With ActiveWorkbook.Worksheets.Add
shName = strFile
ActiveSheet.Name = Replace(shName, ".csv", "")
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Destination:=.Range("A1"))
.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
files(i) = .Parent.Name
i = i + 1
End With
End With
strFile = Dir
Loop
numOfFiles = i - 1
chartName = "Chart 1"
For j = 1 To numOfFiles
If n = 0 Then n = j Else n = n + 2
strFile = files(j)
Sheets(strFile).Select
Plot_y = Range("B1", Selection.End(xlDown)).Rows.Count
Plot_x = Range("C1", Selection.End(xlDown)).Rows.Count
Sheets("GraphDisplay").Select
If j = 1 Then ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(n).Name = strFile & " - Col B Values"
ActiveChart.SeriesCollection(n).XValues = "=" & strFile & "!$C$1:$C$" & Plot_x
ActiveChart.SeriesCollection(n).Values = "=" & strFile & "!$B$1:$B$" & Plot_y
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(n + 1).Name = strFile & " - Col A Values"
ActiveChart.SeriesCollection(n + 1).XValues = "=" & strFile & "!$C$1:$C$" & Plot_x
ActiveChart.SeriesCollection(n + 1).Values = "=" & strFile & "!$A$1:$A$" & Plot_y
ActiveChart.SeriesCollection(j).MarkerStyle = -4142
ActiveChart.SeriesCollection(j).Smooth = False
ActiveChart.SeriesCollection(n + 1).MarkerStyle = -4142
ActiveChart.SeriesCollection(n + 1).Smooth = False
Next j
ActiveSheet.ChartObjects(chartName).Activate
ActiveChart.Axes(xlValue).DisplayUnit = xlMillions
ActiveChart.Axes(xlValue).HasDisplayUnitLabel = False
End Sub

Related

How to read the second and third line of csv as one line

My Excel reads a CSV file to get data for a grid table.
"header", "header", "header", "header"
"value1",
"value2", "value3", "value4"
"value5", "value6", "value7", "value8"
"value9", "value10", "value11", "value12"
I want to read the second and third line of the CSV as the first row of the grid table.
Other lines are read one by one.
My code is:
Dim FileName As String, folder As String
folder = ThisWorkbook.Path & "\"
FileName = Dir(ThisWorkbook.Path & "\*.csv")
With ActiveSheet.QueryTables _
.Add(Connection:="TEXT;" & folder & FileName, Destination:=ActiveCell)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
My approach:
I am trying to modify the csv file with a new one that will have the second and third line merged as the second line.
filePath = folder & fileName
Dim fName As String, fso As Object, fsoFile As Object, txt As Variant
Set fso = CreateObject("Scripting.FileSystemObject")
Set fsoFile = fso.OpenTextFile(filePath, 1)
txt = fsoFile.ReadAll
fsoFile.Close
txt = Split(txt, vbNewLine)
txt(2 - 1) = "some text with special characters like & Char(44) & and & Chr(10) & and so on"
Set fsoFile = fso.OpenTextFile(filePath, 2)
fsoFile.Write Join(txt, vbNewLine)
fsoFile.Close
the problem is that the grid table displays the special characters as & Char(44) & and & Char(10) & inside the cells...
Three methods for combining 2nd and 3rd lines
Sub merge23()
Dim fso As Object, tsIn, tsOut
Dim s As String
Set fso = CreateObject("Scripting.Filesystemobject")
Set tsIn = fso.OpenTextFile("C:\temp\test.csv", 1)
Set tsOut = fso.CreateTextFile("C:\temp\test1.csv", 1)
' method 1
Do While tsIn.AtEndOfLine <> True
s = tsIn.readline
If tsIn.Line <> 3 Then
s = s & vbCrLf
End If
tsOut.write s
Loop
tsIn.Close
tsOut.Close
' method 2
Set tsIn = fso.OpenTextFile("C:\temp\test.csv", 1)
s = tsIn.readall
tsIn.Close
s = Replace(s, vbCrLf, "~#~#~", 1, 1) 'mark 1st crlf
s = Replace(s, vbCrLf, "", 1, 1) ' replace 2nd
s = Replace(s, "~#~#~", vbCrLf, 1, 1) ' replace 1st crlf
Set tsOut = fso.CreateTextFile("C:\temp\test2.csv", 1)
tsOut.writeline s
' method 3 regex
Dim regex
Set regex = CreateObject("vbscript.regexp")
With regex
.Global = False
.MultiLine = True
.Pattern = "^(.*\r\n.*)\r\n" ' 2nd crlf
End With
Set tsIn = fso.OpenTextFile("C:\temp\test.csv", 1)
s = tsIn.readall
tsIn.Close
Set tsOut = fso.CreateTextFile("C:\temp\test3.csv", 1)
s = regex.Replace(s, "$1")
tsOut.writeline s
tsOut.Close
End Sub

Trying to bulk import csv to Excel using VBA, data turns out "slanted"

This is my current VBA code:
Option Explicit
Private Function LoopThroughFolder(RootFolder As String, CsvFolder As String, Status As String)
Dim folder, StrFile As String
Dim wks As Worksheet
folder = RootFolder & "\" & CsvFolder & "\" & Status
StrFile = Dir(folder & "\*.csv")
Do While Len(StrFile) > 0
Set wks = Worksheets(CsvFolder & Status)
ImportCsv folder & "\" & StrFile, wks
StrFile = Dir
Loop
'Debug.Print RootFolder & "\" & CsvFolder & "\" & Status & " >>> OK!"
End Function
Private Function ImportCsv(CsvFile As String, wks As Worksheet)
Dim row&, col As Integer
'Debug.Print CsvFile
row = wks.Cells(Rows.Count, 1).End(xlUp).row
With wks.QueryTables _
.Add(Connection:="TEXT;" & CsvFile, Destination:=wks.Cells(row + 1, 1))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Function
Public Sub ImportFolderCsv()
Dim RootFolder As String
RootFolder = "C:\Users\chinkai\Desktop\dims investigate"
Dim CsvFolders(1 To 2) As String
CsvFolders(1) = "csvVeh"
CsvFolders(2) = "csvCust"
Dim Statuses(1 To 2) As String
Statuses(1) = "FAIL"
Statuses(2) = "PASS"
Dim i, j As Integer
Dim folder As String
Dim ws As Worksheet
For i = 1 To 1
For j = 1 To 2
Sheets.Add.Name = CsvFolders(i) & Statuses(j)
LoopThroughFolder RootFolder, CsvFolders(i), Statuses(j)
Next j
Next i
End Sub
When I open my worksheets to view, the data appears in the form of an inverted triangle. Data from the first CSV goes into the top right corner, data from the second CSV goes below but to the left, so on and so forth, until the last CSV where data appears in the bottom left corner.
What my data looks like:
New to Excel VBA, so most of the code here are copy-pasta. I tried to tweak what I can but now I am not sure where I have gone wrong. Advice/feedback appreciated, thank you!
Edit: made some changes as suggested. Updated my code above and also provided a screen capture of this weird display...
I have played a bit with your code, but I could not replicate the "reversed triangle thing". However, just to make you started somewhere:
Replace the ActiveSheet with a reference of the worksheet, that you should pass as a parameter to the ImportCsv function:
Private Function ImportCsv(CsvFile As String, wks As Worksheet)
Dim row&, col As Long
Debug.Print CsvFile
row = wks.Cells(Rows.Count, 1).End(xlUp).row
With wks.QueryTables _
.Add(Connection:="TEXT;" & CsvFile, Destination:=wks.Cells(row + 1, 1))
And you take the wks like this from the Status string:
Private Function LoopThroughFolder(RootFolder As String, CsvFolder As String, Status As String)
Dim folder, StrFile As String
Dim wks As Worksheet
folder = RootFolder & "\" & CsvFolder & "\" & Status
StrFile = Dir(folder & "\*.csv")
Do While Len(StrFile) > 0
Set wks = Worksheets("csvVeh" & Status)
Two more important points:
write Option Explicit on the top of your module and try to declare all variables. Then go to Debug>Compile on the VBEditor ribbon and declare what is not declared.
as #Peh mentioned in the comments if you declare like this in C++ Dim a, b as Integer, then a and b are Integers. In VBA only b is declared as an Integer, a is a Variant. You should declare Dim a As Integer, b as Integer
Why Use Integer Instead of Long?

"object invoked has disconnected from its clients" Excel 2016

I have seen this asked multiple times but none of the solutions offered have solved my issue- I continue to get this error even though I have used the same code in multiple other applications with no errors. I have included the code below and hope that someone can spot the issue that I am just failing to see!
Sub CreateJobsGraphsPrincipalCategory()
'Initial variables
Dim wbnew As Workbook
Dim wsnew As Worksheet
Dim Datasheet As Worksheet
'Dataset variables
Dim BeneficiaryList(0 To 10000), PrincipalList(0 To 10000), CheckRange As String
Dim NumberRows, RowNumber As Long
Dim Isduplicate, intPrincipal, intStatus, intLineItem As Integer
Dim PrincipalColumn, StatusColumn, LineItemColumn As String
Dim PrincipalRange, StatusRange, LineItemRange As String
Dim PrincipalNumber, BeneficiaryNumber As Integer
'New PivotChart variables
Dim objPivotcache As PivotCache
Dim objPivotTable As PivotTable
Dim bcount As Integer
Dim ProsperatorArray(1 To 25) As String
Dim BusinessNameColumn, BeneficiaryName, BeneficiaryNameFind As String
Dim objPivot As PivotTable, objPivotRange As Range, objChart As Chart
Dim LastColumnNumber As Double
'Setup workbooks
Dim CurrentWorkbook As Workbook
Dim SaveToWorkbook As Workbook
'Stop screen updating and calculating furing processing
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
'Select overall datasheet
Worksheets("DataforPrincipals").Activate
Set Datasheet = ActiveSheet
'Find last column. Start from column 30 as it will not be less than this
LastColumnNumber = 30
LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
While LastColumnValue <> ""
LastColumnNumber = LastColumnNumber + 1
LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
Wend
LastColumnNumber = LastColumnNumber - 1
'LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
LastColumnValue = Getcolumn(LastColumnNumber)
'get last row
LastRowNumber = 1
LastRowRange = "A" & LastRowNumber
LastRowValue = Datasheet.Cells(LastRowNumber, 1)
While LastRowValue <> ""
LastRowNumber = LastRowNumber + 1
LastRowRange = "A" & LastRowNumber
LastRowValue = Datasheet.Cells(LastRowNumber, 1)
Wend
LastRowNumber = LastRowNumber - 1
PivotRange = "A" & "1" & ":" & LastColumnValue & LastRowNumber
'Creating Pivot cache
Set objPivotcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'DataforPrincipals'!" & PivotRange)
'Create Arrays for Beneficiaries and Principals
'Get Columns for filtering and checking
PrincipalColumn = FindDataColumnHeading("Principal")
' StatusColumn = FindDataColumnHeading("Status")
LineItemColumn = FindDataColumnHeading("Line Item")
BusinessNameColumn = FindDataColumnHeading("Business Name")
RowNumber = 2
NumberRows = 0
CheckRange = BusinessNameColumn & RowNumber
PrincipalNumber = 1
BeneficiaryNumber = 1
While Datasheet.Range(CheckRange) <> ""
NumberRows = NumberRows + 1
PrincipalRange = PrincipalColumn & RowNumber
' StatusRange = StatusColumn & RowNumber
LineItemRange = LineItemColumn & RowNumber
' If Datasheet.Range(StatusRange) = "Active" Then
If Datasheet.Range(LineItemRange) = "Turnover" Then
BeneficiaryList(BeneficiaryNumber) = Datasheet.Range(CheckRange)
BeneficiaryNumber = BeneficiaryNumber + 1
'Check if principal is in the dataset yet
If RowNumber = 2 Then
PrincipalList(PrincipalNumber) = UCase(Trim(Datasheet.Range(PrincipalRange)))
Else
PrincipalNumber = PrincipalNumber + 1
Isduplicate = 0
For i = 1 To PrincipalNumber
If PrincipalList(i) = UCase(Trim(Datasheet.Range(PrincipalRange))) Then
Isduplicate = 1
End If
Next i
If Isduplicate = 0 Then
PrincipalList(PrincipalNumber) = UCase(Trim(Datasheet.Range(PrincipalRange)))
Else
PrincipalNumber = PrincipalNumber - 1
End If
End If
End If
' End If
RowNumber = RowNumber + 1
CheckRange = BusinessNameColumn & RowNumber
Wend
Set CurrentWorkbook = Application.ActiveWorkbook
' Set wbnew = Workbooks.Add
'wbnew = ActiveWorkbook.Name
CurrentWorkbook.Activate
For i = 1 To PrincipalNumber
PrincipalNameFind = PrincipalList(i)
If PrincipalList(i) <> PrincipalList(i - 1) Then
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
'Adding new worksheet
Worksheets("DataforPrincipals").Activate
Set wsnew = Worksheets.Add
wsnew.Name = PrincipalName & "JC"
Worksheets(PrincipalName & "JC").Activate
'Creating Pivot table
Set objPivotTable = objPivotcache.CreatePivotTable(wsnew.Range("A1"))
'set Beneficiary row field
'Setting Fields
With objPivotTable
With .PivotFields("Principal")
.Orientation = xlPageField
.CurrentPage = "ALL"
.ClearAllFilters
.CurrentPage = PrincipalNameFind
End With
'set data fields (PI TO, TO)
With .PivotFields("Category")
.Orientation = xlRowField
End With
.AddDataField .PivotFields("PI Total Staff"), "PI Jobs", xlSum
.AddDataField .PivotFields("Current Total Staff"), "Current Jobs", xlSum
.AddDataField .PivotFields("Job Growth"), "Job Growth ", xlSum
With .PivotFields("PI Jobs")
.NumberFormat = "#"
End With
With .PivotFields("Current Jobs")
.NumberFormat = "#"
End With
With .PivotFields("Job Growth ")
.NumberFormat = "#%"
End With
End With
' Access the new PivotTable from the sheet's PivotTables collection.
Set objPivot = ActiveSheet.PivotTables(1)
' Add a new chart sheet.
Set objChart = Charts.Add
' Create a Range object that contains
' all of the PivotTable data, except the page fields.
Set objPivotRange = objPivot.TableRange1
' Specify the PivotTable data as the chart's source data.
With objChart
.ShowAllFieldButtons = False
.SetSourceData objPivotRange
.ChartType = xlColumnClustered
.ApplyLayout (5)
With .ChartTitle
.Text = " Employment Growth performance per Category"
End With
.SeriesCollection(1).HasDataLabels = False
.SeriesCollection(2).HasDataLabels = False
.SeriesCollection(3).HasDataLabels = False
.Axes(xlCategory).HasTitle = False
.DataTable.Select
End With
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
ActiveSheet.Name = PrincipalName & " JCG"
If Sheetslist = "" Then
Sheetslist = PrincipalName & " JCG"
Else
Sheetslist = Sheetslist & ", " & PrincipalName & " JOBS"
End If
End If
Next i
'Copy to new file
Set CurrentWorkbook = Application.ActiveWorkbook
DirectoryName = Sheets("Run Automated").Range("B1")
For i = 1 To PrincipalNumber
If PrincipalList(i) <> PrincipalList(i - 1) Then
With Worksheets("Run Automated")
NameFileInitial = .Range("B2") & " " & PrincipalList(i) & ".xlsm"
End With
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
'Set sheets to save
sheet1save = PrincipalName & " TC"
sheet2save = PrincipalName & " TOC"
sheet7save = PrincipalName & "JC"
sheet8save = PrincipalName & " JCG"
Set CurrentWorkbook = Application.ActiveWorkbook
Namefile = DirectoryName & "\" & NameFileInitial
Workbooks.Open Namefile
Set SaveToWorkbook = Application.ActiveWorkbook
Application.DisplayAlerts = False
CurrentWorkbook.Sheets(Array(sheet1save, sheet2save, sheet7save, sheet8save)).Move Before:=SaveToWorkbook.Sheets(1)
ActiveWorkbook.Close (True)
Application.DisplayAlerts = True
CurrentWorkbook.Activate
End If
Next i
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
End Sub

All possible combinations of 10 numbers with repetition in excel

How can i generate all possible combinations of numbers {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } with length 5 in Excel. I know there are 10^5 possible combinations with repetition.
Thank you
A slight modification of elene's code.
Sub AllCombinations()
Dim nums(): nums = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Dim arValues(99999, 4)
Dim n1 As Integer, n2 As Integer, n3 As Integer, n4 As Integer, n5 As Integer, x As Long
For n1 = 0 To UBound(nums)
For n2 = 0 To UBound(nums)
For n3 = 0 To UBound(nums)
For n4 = 0 To UBound(nums)
For n5 = 0 To UBound(nums)
arValues(x, 0) = nums(n1)
arValues(x, 1) = nums(n2)
arValues(x, 2) = nums(n3)
arValues(x, 3) = nums(n4)
arValues(x, 4) = nums(n5)
x = x + 1
Next
Next
Next
Next
Next
Range("A1").Resize(100000, 5).Value2 = arValues
End Sub
This might run a bit faster:
Sub combinations()
Dim wb As Workbook, i As Integer, strFileName As String
'Create Temp Workbook for data source
Set wb = Workbooks.Add
With wb.ActiveSheet
.Range("A1").Value = "Integer"
For i = 0 To 9
.Range("A" & i + 2).Value = i
Next i
End With
strFileName = "C:\Temp\Temp.xlsx"
wb.SaveAs strFileName
wb.Close False
'Create List using Temp Workbook as source(s)
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array("ODBC;DBQ=" & strFileName & ";DefaultDir=C:\temp;Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DriverId=1046;FIL=exce"), Array("l 12.0;MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;ReadOnly=1;SafeTransactions=0;Threads=3;UID=admin;UserCommitSync=Yes;")), Destination:=Range("$A$1")).QueryTable
.CommandText = Array( _
"SELECT `Sheet1$`.Integer, `Sheet1$_1`.Integer, `Sheet1$_2`.Integer, `Sheet1$_3`.Integer, `Sheet1$_4`.Integer" & Chr(13) & "" & Chr(10) & "FROM `" & strFileName & "`.`Sheet1$` `Sheet1$`, `" & strFileName & "`.`Sheet1$` `Sheet1$_1`, `", strFileName & "`.`Sheet1$` `Sheet1$_2`, `" & strFileName & "`.`Sheet1$` `Sheet1$_3`, `" & strFileName & "`.`Sheet1$` `Sheet1$_4`")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_Temp"
.Refresh BackgroundQuery:=False
End With
'Convert back to range
ActiveSheet.ListObjects("Table_Query_from_Temp").Unlist
'Delete top row
Rows("1:1").Delete
'Delete Temp file
Kill strFileName
End Sub
Well faster than the original. Probably not a lot in it for the array approach. It's a different technique at least...

Compile an Excel VBA Script to modify a connection property in another workbook

I have a workbook that contains a macro that i wish to use to update the location of a connection in another workbook. The VBA script creates a folder, populates it with a log file containing data called log.txt and a copy of an excel file that is pre formatted to fill with the data allowing the user to see graphs and a detailed breakdown of the data. it is a door opening log, tracking numbers of times the door has been used.
here is the VBA code I've come up with so far.
note: I did a couple of years programming in C++ but haven't touched it in a decade. I have tried searching around for the code and even recording a macro of the actions I take when refreshing the connection manually. however if I try and use that code it gives a "Run time error 1004" Application defined or object defined error.
Here is the code. The commented out bit at the bottom is the result of the macro recorded from manually altering the connection.
Any help would be greatly received.
Sub Lof_File_Macro()
' Log_file_Macro Macro
' Runs script for monthly counts '
Dim strfolder1, strmonthno, strmonth, stryear, strfoldername, strfile, strmonyr, stlogfile, strfutfile
'date strings defined using date functions - ofset for 28 days to allow running anytime within 20 days into the next month whilereturning correct month
strmonthno = Month(Date - 28)
strmonth = MonthName((strmonthno), True)
stryear = Year(Date - 28)
strmonyr = " " & strmonth & " " & stryear
strfolder = "C:\Users\jtaylor7\Desktop\futures\People Counter" & strmonyr
strfile = "Futures People" & strmonyr & ".xls"
strlogfile = strfolder & "\" & "log" & strmonyr & ".txt"
strfutfile = strfolder & "\" & strfile
MkDir (strfolder)
FileCopy "C:\Users\jtaylor7\Desktop\futures\log.log", strlogfile
FileCopy "C:\Users\jtaylor7\Desktop\futures\template.xls", strfutfile
'Workbooks.Open Filename:=strfutfile
'ActiveWorkbook.Connections.AddFromFile (strlogfile)
'
'
' Perform data connection modification on file
'' Windows(strfutfile).Activate
' With ActiveWorkbook.Connections("log")
' .Name = "log"
' .Description = ""
' End With
' Range("$A$1:$H$1").Select
'With Selection.QueryTable
' .Connection = "TEXT;strlogfile"
' .TextFilePlatform = 850
' .TextFileStartRow = 1
' .TextFileParseType = xlDelimited
' .TextFileTextQualifier = xlTextQualifierDoubleQuote
' .TextFileConsecutiveDelimiter = False
' .TextFileTabDelimiter = False
' .TextFileSemicolonDelimiter = False
' .TextFileCommaDelimiter = True
' .TextFileSpaceDelimiter = False
' .TextFileOtherDelimiter = "/"
' .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
' .TextFileTrailingMinusNumbers = True
' .Refresh BackgroundQuery:=False
' End With
' Range("I4").Select
' ActiveWorkbook.Connections("log").Refresh
'' Windows("Run Me.xls").Activate
'
End Sub
I know its a bit messy, and if anyone needs any further data please ask.
Something like this should do the trick.
Pls update your paths from my testing below
Sub LogFile_Macro()
Dim strFolder As String
Dim strMonthno As String
Dim strMonth As String
Dim strYear As String
Dim strFoldername As String
Dim strFile As String
Dim strMonyr As String
Dim strLogfile As String
Dim strFutfile As String
Dim wb As Workbook
'date strings defined using date functions - ofset for 28 days to allow running anytime within 20 days into the next month whilereturning correct month
strMonthno = Month(Date - 28)
strMonth = MonthName((strMonthno), True)
strYear = Year(Date - 28)
strMonyr = " " & strMonth & " " & strYear
strFolder = "C:\temp\People Counter" & strMonyr
strFile = "Futures People" & strMonyr & ".xls"
strLogfile = strFolder & "\" & "log" & strMonyr & ".txt"
strFutfile = strFolder & "\" & strFile
On Error Resume Next
MkDir strFolder
If Err.Number <> 0 Then
MsgBox "cannot create path", vbCritical
Exit Sub
End If
On Error GoTo 0
FileCopy "C:\temp\futures\log.log", strLogfile
FileCopy "C:\temp\futures\template.xls", strFutfile
Set wb = Workbooks.Open(strFutfile)
With wb.Sheets(1).QueryTables.Add(Connection:="TEXT;" & strLogfile, Destination:=Range("A1:H1"))
.Name = "log"
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileCommaDelimiter = True
.TextFileOtherDelimiter = "/"
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
.Refresh
End With
Windows("Run Me.xls").Activate
End Sub

Resources