How to create ONE sub function from repetitive sub-functions - vba

I have created a code where I automate text files, outputting column data from an excel macro, in a specific format. I have created 5 different sub methods where they all contain almost the same lines of code. However, there are two lines of code that change for each sub. I would like to create just ONE sub just to simplify the coding for the user. The end goal is to have just one function that can be called and automatically generate the other output files (from sub test1, sub test2, sub test3, sub test4).
Below is one of the sub function code. The rest are the same except for the following lines:
stream.Write "EQUIPMENT_ID_DEF,02,0x1" & "," & Chr(34) & "ic1080_1" & Chr(34)
For the above line what changes is the 0x1 (it increases) and the "ic1080_1" which changes its name to test1, test2, etc...
If destgroup = "ic1080_1" And ssystem = "A429" And sformat = "BNR" Then
For the above line what changes is the "ic1080_1" name for the other sub names (test1, test2, etc...)
Sub ic1080_1(Path, IDnum As Integer, parmgroup As String)
'Declaring variables
Dim equipID As String, destgroup As String, sourceparmname As String, descript As String
Dim lsb As Integer, msb As Integer, signed As String, sformat As String, units As String
Dim scalefact As Variant, numbits As Integer, decim As Integer
Dim ssystem As String
Dim FName As String, stream As TextStream
Dim fso As Scripting.FileSystemObject
Dim vDB
Set fso = New Scripting.FileSystemObject
'Create txt file
Set stream = fso.CreateTextFile(Path)
'Activate Sheet1
Sheet1.Activate
With Sheet1
vDB = .Range("a1").CurrentRegion 'Get data to array from excel data range
n = UBound(vDB, 1) 'Size of array (row of 2 dimension array)
End With
'Open text file to write data
stream.Write "EQUIPMENT_ID_DEF,02,0x" & IDnum & "," & Chr(34) & parmgroup & Chr(34)
'Create arrays for each row of data
For i = 2 To n
destgroup = vDB(i, 15) '15th columm array(destination group)
ssystem = vDB(i, 7) '7th columm array(source system)
sformat = vDB(i, 32) '32nd columm array(format)
sourceres = vDB(i, 11) '11th column array(source resolution)
If destgroup = parmgroup And ssystem = "A429" And sformat = "BNR" Then
sourceparmname = format(Val(Replace(vDB(i, 8), "label ", "")), "0000")
descript = vDB(i, 3)
signed = Val(Replace(vDB(i, 33), "Yes", 1))
msb = vDB(i, 34)
lsb = vDB(i, 35)
units = vDB(i, 6)
numbits = (msb - lsb + 1) 'Calculates the number of bits
scalefact = sourceres * (2 ^ (numbits)) 'Computes the scale factor by: source resolution *(2^(msb-lsb+1))
decim = 9
'Write data into text file
stream.Write vbCrLf & "; #### LABEL DEFINITION ####" & vbCrLf & _
"EQ_LABEL_DEF,02," & sourceparmname & vbCrLf & _
"UDB_LABEL," & Chr(34) & descript & Chr(34) & vbCrLf & _
"STD_SUB_LABEL," & Chr(34) & descript & Chr(34) & "," & lsb & "," & msb & "," & signed & vbCrLf & _
"STD_ENCODING," & Chr(34) & sformat & Chr(34) & "," & Chr(34) & units & Chr(34) & "," & scalefact & "," & numbits & "," & decim & vbCrLf & _
"END_EQ_LABEL_DEF"
End If
'Continue looping until the last row
Next i
stream.Write vbCrLf & "; #### END EQUIPMENT ID DEFINITION ####" & vbCrLf & _
"END_EQUIPMENT_ID_DEF"
'Close the text file
stream.Close
End Sub
I also created another sub that calls all the subs ("ic1080_1", test1, test2, test3, test4) to output all the text files and saves them into a folder:
Sub txt_files()
Dim fso As Scripting.FileSystemObject, NewFolderPath As String
Dim Path As String
'Retrieve Target Folder Path From User
NewFolderPath = Application.GetSaveAsFilename("")
Set fso = New Scripting.FileSystemObject
If Not fso.FolderExists(NewFolderPath) Then
fso.CreateFolder NewFolderPath
End If
'Call sub functions to generate text files and store them in NewFolderPath
Call ic1080_1.ic1080_1(NewFolderPath & "\ic1080_1.txt", 3, "ic1080_1")
Call ic1080_1.ic1080_1(NewFolderPath & "\test1.txt", 4, "test1")
End Sub

Pass the bits that change between the subroutines as parameters:
Sub txt_files()
'...
'Call sub function to generate text files and store them in NewFolderPath
GenericSub NewFolderPath, "ic1080_1", "1"
GenericSub NewFolderPath, "test1", "2"
GenericSub NewFolderPath, "test2", "3"
GenericSub NewFolderPath, "test3", "4"
GenericSub NewFolderPath, "test4", "5"
End Sub
Sub GenericSub(Path As String, something As String, somethingElse As String)
'...
Set stream = fso.CreateTextFile(Path & "\" & something & ".txt")
'...
stream.Write "EQUIPMENT_ID_DEF,02,0x" & somethingElse & "," & _
Chr(34) & something & Chr(34)
'...
If destgroup = something And ssystem = "A429" And sformat = "BNR" Then
'...
End If
'...
End Sub
I may not have picked up on all the places where you are using the different parameters, but that should give you something to go on.
And please don't use names such as something and somethingElse and even GenericSub - use something meaningful to describe them. I just used those names because I wasn't sure what they meant.

Related

To move files from multiple source folders to multiple destination folders based on two hour delay

Yesterday we have finalized and tested the code (the first part of the code is VBScript) and the second part of the code is (in Excel VBA) to move file from one source folder to one destination folder successfully based on two hour delay (i.e. each file which will come to source folder will upload 2 hour delay), however the situation is that i have actually 15 source folders and 15 destination folders.
One method is that i should create 15 VBScript files and 15 Excel files that contains the code for each source and destination folder which i believe is not efficient way. I have tried a lot to add multiple source and destination folder options in the below mentioned code(s) but i am not successful, can anyone help me, i will be thankful.
the below mentioned code is VBscript
Dim oExcel, strWB, nameWB, wb
strWB = "E:\Delta\Folder monitor.xlsm"
nameWB = Left(strWB, InStr(StrReverse(strWB), "\") - 1)
nameWB = Right(strWB, Len(nameWB))
Set objExcel = GetObject(,"Excel.Application")
Set wb = objExcel.Workbooks(nameWB)
if wb is nothing then wbscript.quit 'the necessary workbook is not open...
dim strComputer, strDirToMonitor, strTime, objWMIService, colMonitoredEvents, objEventObject, MyFile
strComputer = "."
'# WMI needs two backslashes (\\) as path separator and each of it should be excaped.
'# So, you must use 4 backslashes (\\\\) as path separator!
strDirToMonitor = "E:\\\\Delta\\\\Source" 'use here your path
'# Monitor Above every 10 secs...
strTime = "10"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceOperationEvent WITHIN " & strTime & " WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=" & Chr(34) & strDirToMonitor & Chr(34) & "'")
Do While True
Set objEventObject = colMonitoredEvents.NextEvent()
Select Case objEventObject.Path_.Class
Case "__InstanceCreationEvent"
' msgbox "OK"
'MsgBox "A new file was just created: " & _
MyFile = StrReverse(objEventObject.TargetInstance.PartComponent)
'// Get the string to the left of the first \ and reverse it
MyFile = (StrReverse(Left(MyFile, InStr(MyFile, "\") - 1)))
MyFile = Mid(MyFile, 1, Len(MyFile) - 1)
'send the information to the waiting workbook:
objExcel.Application.Run "'" & strWB & "'!GetMonitorInformation", Array(MyFile,Now)
End Select
Loop
and the second code for this purpose should be copied in a standard module:
Option Explicit
Private Const ourScript As String = "FolderMonitor.vbs"
Private Const fromPath As String = "E:\Delta\Source\"
Sub startMonitoring()
Dim strVBSPath As String
strVBSPath = ThisWorkbook.Path & "\VBScript\" & ourScript
TerminateMonintoringScript 'to terminate monitoring script, if running..
Shell "cmd.exe /c """ & strVBSPath & """", 0
End Sub
Sub TerminateMonintoringScript()
Dim objWMIService As Object, colItems As Object, objItem As Object, Msg
As String
Set objWMIService = GetObject("winmgmts:\\" & "." & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL", 48)
For Each objItem In colItems
If objItem.Caption = "wscript.exe" Then
'// msg Contains the path of the exercutable script and the script name
On Error Resume Next
Msg = objItem.CommandLine 'for the case of null
On Error GoTo 0
'// If wbscript.exe runs the monitoring script:
If InStr(1, Msg, ourScript) > 0 Then
Debug.Print "Terminate Wscript process..."
objItem.Terminate 'terminate process
End If
End If
Next
Set objWMIService = Nothing: Set colItems = Nothing
End Sub
Sub GetMonitorInformation(arr As Variant)
'call DoSomething Sub after 2 hours (now IT WILL RUN AFTER 1 MINUTE, for testing reasons...)
'for running after 2 hours you should change "00:01:00" in "02:00:00":
arr(0) = Replace(arr(0), "'", "''") 'escape simple quote (') character'
Application.OnTime CDate(arr(1)) + TimeValue("00:01:00"), "'DoSomething """ & CStr(arr(0)) & """'"
Debug.Print "start " & Now 'just for testing (wait a minute...)
'finaly, this line should be commented.
End Sub
Sub DoSomething(strFileName As String)
Const toPath As String = "E:\Delta\Destination\"
If Dir(toPath & strFileName) = "" Then
Name fromPath & strFileName As toPath & strFileName
Debug.Print strFileName & " moved from " & fromPath & " to " & toPath 'just for testing...
Else
MsgBox "File """ & toPath & strFileName & """ already exists in this location..."
End If
End Sub
you can see the previous query here on the link Previous Query
Please, use the next scenario. It assumes that you will fill the necessary path in an existing Excel sheet. Since, it will take the necessary paths based on a cell selection, it is necessary to name the sheet in discussion as "Folders". In Column A:A you should fill the 'Source' folder path (ending in backslash "") and in B:B, the 'Destination' folder path (also ending in backslash).
The proposed solution takes the necessary paths based on your selection in A:A column. The 'Destination' path is extracted based on the selection row.
Please, replace the existing string with the next one, adapting the two necessary paths:
Dim oExcel, strWB, nameWB, wb
strWB = "C:\Teste VBA Excel\Folder monitor.xlsm" 'use here your workbook path!!!
nameWB = Left(strWB, InStr(StrReverse(strWB), "\") - 1)
nameWB = Right(strWB, Len(nameWB))
Set objExcel = GetObject(,"Excel.Application")
Set wb = objExcel.Workbooks(nameWB)
if wb is nothing then wbscript.quit 'the necessary workbook is not open...
dim strComputer, strDirToMonitor, strTime, objWMIService, colMonitoredEvents, objEventObject, MyFile
strComputer = "."
'# WMI needs two backslashes (\\) as path separator and each of it should be excaped.
'# So, you must use 4 backslashes (\\\\) as path separator!
strDirToMonitor = "C:\\\\test\\\\test" 'use here your path !!!
'# Monitor Above every 10 secs...
strTime = "10"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceOperationEvent WITHIN " & strTime & " WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=" & Chr(34) & strDirToMonitor & Chr(34) & "'")' and " _
' & "'Win32_Directory.Name=" & Chr(34) & strDirToMonitor & Chr(34) & "'")
Do While True
Set objEventObject = colMonitoredEvents.NextEvent()
Select Case objEventObject.Path_.Class
Case "__InstanceCreationEvent"
MyFile = StrReverse(objEventObject.TargetInstance.PartComponent)
' Get the string to the left of the first \ and reverse it
MyFile = (StrReverse(Left(MyFile, InStr(MyFile, "\") - 1)))
MyFile = Mid(MyFile, 1, Len(MyFile) - 1)
'send the information to the waiting workbook:
objExcel.Application.Run "'" & strWB & "'!GetMonitorInformation", Array(MyFile, Now, strDirToMonitor)
End Select
Loop
The adapted script sends also the source path to the waiting workbook...
TerminateMonintoringScript Sub remains exactly as it is.
Please, copy the next adapted code instead of existing one, in the used standard module (TerminateMonintoringScript included, even not modified):
Option Explicit
Private Const ourScript As String = "FolderMonitor.vbs"
Private fromPath As String, toPath As String
Sub startMonitoring()
Dim strVBSPath As String, actCell As Range, strTxt As String, pos As Long, endP As Long, oldPath As String
Set actCell = ActiveCell
If actCell.Parent.Name <> "Folders" Then MsgBox "Wrong activated sheet...": Exit Sub
fromPath = actCell.Value
If actCell.Column <> 1 Or Dir(fromPath, vbDirectory) = "" Then Exit Sub 'not a valid path in the selected cell
strVBSPath = ThisWorkbook.Path & "\VBScript\" & ourScript
'change the script necessary "strDirToMonitor" variable path, if the case:__________________________
strTxt = ReadFile(strVBSPath)
pos = InStr(strTxt, Replace(fromPath, "\", "\\\\"))
If pos = 0 Then 'if not the correct path already exists
pos = InStr(strTxt, "strDirToMonitor = """) 'start position of the existing path
endP = InStr(strTxt, """ 'use here your path") 'end position of the existing path
'extract existing path:
oldPath = Mid(strTxt, pos + Len("strDirToMonitor = """), endP - (pos + Len("strDirToMonitor = """)))
strTxt = Replace(strTxt, oldPath, _
Replace(Left(fromPath, Len(fromPath) - 1), "\", "\\\\")) 'replacing existing with the new one
'drop back the updated string in the vbs file:
Dim iFileNum As Long: iFileNum = FreeFile
Open strVBSPath For Output As iFileNum
Print #iFileNum, strTxt
Close iFileNum
End If
'__________________________________________________________________________________________________
TerminateMonintoringScript 'to terminate monitoring script, if running...
Application.Wait Now + TimeValue("00:00:02") 'to be sure that the next line will load the updated file...
Shell "cmd.exe /c """ & strVBSPath & """", 0 'run the VBScript
End Sub
Function ReadFile(strFile As String) As String 'function to read the vbscript string content
Dim iTxtFile As Integer
iTxtFile = FreeFile
Open strFile For Input As iTxtFile
ReadFile = Input(LOF(iTxtFile), iTxtFile)
Close iTxtFile
End Function
Sub TerminateMonintoringScript()
Dim objWMIService As Object, colItems As Object, objItem As Object, Msg As String
Set objWMIService = GetObject("winmgmts:\\" & "." & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL", 48)
For Each objItem In colItems
If objItem.Caption = "wscript.exe" Then
'// msg Contains the path of the exercutable script and the script name
On Error Resume Next
Msg = objItem.CommandLine 'for the case of null
On Error GoTo 0
'// If wbscript.exe runs the monitoring script:
If InStr(1, Msg, ourScript) > 0 Then
Debug.Print "Terminate Wscript process..."
objItem.Terminate 'terminate process
End If
End If
Next
Set objWMIService = Nothing: Set colItems = Nothing
End Sub
Sub GetMonitorInformation(arr As Variant)
'call DoSomething Sub after 2 hours (now IT WILL RUN AFTER 1 MINUTE, for testing reasons...)
'for running after 2 hours you should change "00:01:00" in "02:00:00":
arr(0) = Replace(arr(0), "'", "''") 'escape simple quote (') character'
fromPath = Replace(arr(2), "\\\\", "\")
Dim rngFrom As Range: Set rngFrom = ThisWorkbook.Sheets("Folders").Range("A:A").Find(what:=fromPath)
toPath = rngFrom.Offset(, 1).Value
Application.OnTime CDate(arr(1)) + TimeValue("00:00:30"), "'DoSomething """ & fromPath & "\" & CStr(arr(0)) & """, """ & toPath & CStr(arr(0)) & """'"
Debug.Print Now; " start " & arr(0) & fromPath & "\" & CStr(arr(0)) 'just for testing (wait a minute...)
'finaly, this line should be commented.
End Sub
Sub DoSomething(sourceFileName As String, destFilename As String)
If Dir(destFilename) = "" Then
Name sourceFileName As destFilename
Debug.Print sourceFileName & " moved to " & destFilename 'just for testing...
Else
Debug.Print "File """ & destFilename & """ already exists in this location..."
End If
End Sub
Sub DoSomething_(strFileName As String) 'cancelled
If Dir(toPath & strFileName) = "" Then
Name fromPath & strFileName As toPath & strFileName
Debug.Print strFileName & " moved from " & fromPath & " to " & toPath 'just for testing...
Else
MsgBox "File """ & toPath & strFileName & """ already exists in this location..."
End If
End Sub
So, you only need to replace the existing VBA code with the above adapted one, to place the 'source'/'destination' paths in columns A:B of one of Excel sheets, which to be named "Folders".
Select in column A:A a 'Source' cell and run startMonitoring.
Play with files creation and check their moving from the new 'source' to the new 'destination'...
But you have to understand that only a session of the WMI class can run at a specific moment. This means that you cannot simultaneously monitor more than one folder...
I am still documenting regarding the possibility to use a query able to be common for multiple folders. But I never could see such an approach till now and it may not be possible...

VBA Replace last field in ALL rows within csv around double quotes?

On Error Resume Next
Set FileSysObj = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1 ' Declare constant for reading for more clarity
Dim cntFile, strCSVFullFile, strCSVFile, strDIR, cntBadLines, cntAllLines, strArchiveDir, strSafeTime,strSafeDate
' -------------------------------------------------------------------------------------------
' Specify CSV file name from the input argument
strCSVFile = Wscript.Arguments(1) ' Transactions
strDIR = Wscript.Arguments(2) & "\" ' C:\Temp
strArchiveDir = Wscript.Arguments(3) & "\"
strSafeTime = Right("0" & Hour(Now), 2) & Right("0" & Minute(Now), 2) & Right("0" & Second(Now), 2)
strSafeDate = Year(Date) & Month(Date) & day(Date)
set folder = FileSysObj.getFolder(strDIR)
cntFile = 0
cntBadLines = 0
cntAllLines = 0
for each file in folder.Files
' check if the file is there and echo it.
if InStr(1,file.name,strCSVFile,1) <> 0 then
strCSVFullFile = file.name
cntFile = cntFile + 1
end if
next
if cntFile > 1 or cntFile = 0 then
' error and end
Wscript.Echo "Error - only 1 file required for this process. There are " & cntFile & " file(s) in the directory"
WScript.Quit
end if
wscript.echo "Checking the file " & strCSVFullFile & " in " & strDIR
NoOfCols = Wscript.Arguments(0) ' usually 8
strTemp = "temp.csv"
strmissing = "missingdata.csv"
Set objOutFile = FileSysObj.CreateTextFile(strDIR & strTemp,True)
Set objOutFileM = FileSysObj.CreateTextFile(strDIR & strmissing,True)
Set inputFile = FileSysObj.OpenTextFile(strDIR & strCSVFullFile, ForReading, True)
' Set inputFile as file to be read from
Dim row, column, outline
Dim fields '(7) '8 fields per line
inputFile.ReadAll 'read to end of file
outline = ""
ReDim MyArray(inputFile.Line-2,NoOfCols) 'current line, minus one for header, and minus one for starting at zero
inputFile.close 'close file so that MyArray can be filled with data starting at the top
Set inputFile = FileSysObj.OpenTextFile(strDIR & strCSVFullFile, ForReading, True) 'back at top
strheadLine = inputFile.ReadLine 'skip header , but keep it for the output file
objOutFile.Write(strheadLine & vbCrLf)
anyBadlines = False
badlineflag = False
Do Until inputFile.AtEndOfStream
fullLine = inputFile.Readline
fields = Split(fullLine,",") 'store line in temp array
For column = 0 To NoOfCols-1 'iterate through the fields of the temp array
myArray(row,column) = fields(column) 'store each field in the 2D array with the given coordinates
'Wscript.Echo myArray(row,column)
if myArray(row,0) = " " or myArray(row,1) = " " then
badlineflag = True
'missline = myArray(row,0) & ", " & myArray(row,1) & ", " & myArray(row,2) & ", " & myArray(row,3) & ", " & myArray(row,4) & ", " & myArray(row,5) & ", " & myArray(row,6) & ", " & myArray(row,7)
'Wscript.Echo missline
'Exit For
end if
if column = NoOfCols-1 then
outline = outline & myArray(row,column) & vbCrLf
else
outline = outline & myArray(row,column) & ","
'csvFile = Regex.Replace(csvFile, "(,\s*?"".*?)(,)(\s+.*?""\s*?,)", "$1$3") 'TEST
end if
Next
cntAllLines = cntAllLines + 1
' Wscript.Echo outline
if badlineflag = False then
objOutFile.Write(fullLine & vbCrLf)
else
' write it somewhere else, drop a header in the first time
if anyBadlines = False Then
objOutFileM.Write(strheadLine & vbCrLf)
End if
objOutFileM.Write(outline)
cntBadLines = cntBadLines + 1
badlineflag = False
anyBadlines = True
end if
outline = ""
row = row + 1 'next line
Loop
objOutFile.Close
objOutFileM.Close
inputFile.close
Wscript.Echo "Total lines in the transaction file = " & cntAllLines
Wscript.Echo "Total bad lines in the file = " & cntBadLines
The below line is able to work as it contains 7 commas (8 columns).
URXW_99,BYQ0JC6,2603834418,2017-10-30,Test,4.962644,2278.0000,ABC
The below line will throw an error as a result of more commas than 7 in the script.
URXW_99,BYQ0JC6,2603834418,2017-10-30,Test,4.962644,2278.0000,Redburn, Europe. Limited
If greater than 7 commas in the CSV file line, the aim is to wrap it all greater than 7 into one field.
E.g. how do you replace Redburn, Europe. Limited string with double quotes as it is one name.
For example, in a text file it would appear like below:
URXW_99,BYQ0JC6,2603834418,2017-10-30,Test,4.962644,2278.0000,"Redburn, Europe. Limited"
Is there a way to write a VB or VBA script to do the above and save it as a .csv file (which is opened via notepad to check the double quotes)?
Option Explicit
Option Compare Text
Public Sub ConvertFile()
Dim lngRowNumber As Long
Dim strLineFromFile As String
Dim strSourceFile As String
Dim strDestinationFile As String
strSourceFile = "U:\Book3.csv"
strDestinationFile = "U:\Book4.csv"
Open strSourceFile For Input As #1
Open strDestinationFile For Output As #2
lngRowNumber = 0
Do Until EOF(1)
Line Input #1, strLineFromFile
strLineFromFile = Right(Replace(strLineFromFile, ",", " ", 1), 1000)
Write #2, strLineFromFile
strLineFromFile = vbNullString
Loop
Close #1
Close #2
End Sub
As I see, you use MS Access (due to Option Compare Text line), so there is better built-in instruments for this task.
Use DoCmd.TransferText for it.
1st step is to create output specification via:
Here you can setup delimiters, even that differs from ", and handle other options.
After that you can use your set-up specification via following command
DoCmd.TransferText acExportDelim, "TblCustomers_export_spec", "TblCustomers", "C:\test\1.txt", True
In this case all characters escaping would be done through built-in instruments. It seems to be more easier to correct this code further.
As mentioned, there is VBScript workaround. For given input data, following function will do desired actions for given string:
Option Explicit
Function funAddLastQuotes( _
strInput _
)
Dim arrInput
arrInput = Split(strInput, ",")
Dim intArrSize
intArrSize = UBound(arrInput)
Dim intCurrentElement
Dim strOutput
Dim intPreLastElement
intPreLastElement = 6
For intCurrentElement = 1 To intPreLastElement
strOutput = strOutput & "," & arrInput(intCurrentElement)
Next
Dim strOutputLastField
For intCurrentElement = intPreLastElement + 1 To intArrSize
strOutputLastField = strOutputLastField & "," & arrInput(intCurrentElement)
Next
strOutputLastField = Right(strOutputLastField, Len(strOutputLastField) - 1)
strOutput = Right(strOutput, Len(strOutput) - 1)
strOutput = strOutput & "," & """" & strOutputLastField & """"
funAddLastQuotes = strOutput
End Function
MsgBox funAddLastQuotes("RXW_99,BYQ0JC6,2603834418,2017-10-30,Test,4.962644,2278.0000,Redburn, Europe,,, Limited")
Finally, here is working VBScript solution.
Option Explicit
Const ColumnsBeforeCommadColumn = 6
Function funAddLastQuotes( _
strInput _
)
Dim arrInput
arrInput = Split(strInput, ",")
Dim intArrSize
intArrSize = UBound(arrInput)
Dim intCurrentElement
Dim strOutput
Dim intPreLastElement
intPreLastElement = ColumnsBeforeCommadColumn
For intCurrentElement = 1 To intPreLastElement
strOutput = strOutput & "," & arrInput(intCurrentElement)
Next
Dim strOutputLastField
If (intPreLastElement + 1) < intArrSize _
Then
For intCurrentElement = intPreLastElement + 1 To intArrSize
strOutputLastField = strOutputLastField & "," & arrInput(intCurrentElement)
Next
Else
strOutputLastField = strOutputLastField & "," & arrInput(intArrSize)
End If
strOutputLastField = Right(strOutputLastField, Len(strOutputLastField) - 1)
strOutput = Right(strOutput, Len(strOutput) - 1)
strOutput = strOutput & "," & """" & strOutputLastField & """"
funAddLastQuotes = strOutput
End Function
Public Sub ConvertFile( _
strSourceFile _
)
Dim objFS
Dim strFile
Dim strTemp
Dim ts
Dim objOutFile
Dim objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Dim strLine
Dim strOutput
Dim strRow
strFile = strSourceFile
strTemp = strSourceFile & ".tmp"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do Until ts.AtEndOfStream
strLine = ts.ReadLine
objOutFile.WriteLine funAddLastQuotes(strLine)
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile
End Sub
ConvertFile "C:\!accsoft\_in.csv"
You should change following part: ConvertFile "C:\!accsoft\_in.csv as path to your file.
And ColumnsBeforeCommadColumn = 6 is the setting, at which column the chaos with commas begins

Run-Time Error 40046: Statement too complex

I'm trying to write a code module using the InsertLines method, but am getting the
Statement too complex Error
My code boils down to this loop:
Dim extractorModule As VBComponent
With extractorModule.codeModule
Dim singItem As codeItem
Dim i As Long
For i = LBound(codeItems) To UBound(codeItems)
singItem = codeItems(i) 'array of private type with .value property
.InsertLines 5, singItem.value 'write to line 5
Next i
End With
Which loops through an array of custom codeItems, and writes their .value to a new module with .InsertLines
singItem.value is a base64 encoded string. If it is a short one, 100 characters say, like this string:
.code_content = "QXR0cmlidXRlIFZCX05hbWUgPSAic2ltcGxlTW9kdWxlIg0KUHJpdmF0ZSBhIEFzIExvbmcNCg=="
no problem. However I want a longer string, this one for example (19000 chars, contains newlines):
.code_content = "QXR0cmlidXRlIFZCX05hbWUgPSAicHJvamVjdENvbXByZXNzb3IiDQonQ29tcHJlc3NvciBtb2R1bGUsIGNvbXByZXNzZXMgYSBsb2FkIG9mIGZpbGVzIGludG8gc3RyaW5ncyB0byBleHBvcnQNCk9wdGlvbiBFeHBsaWNpdA0KUHJpdmF0ZSBUeXBlIGNvZGVJdGVtDQogICAgZXh0ZW5zaW9uIEFzIFN0cmluZw0KICAgIG1vZHVsZV9uYW1lIEFzIFN0cmluZw0KICAgIGNvZGVfY29udGVudCBBcyBTdHJpbmcNCkVuZCBUeXBlDQpQcml2YXRlIENvbnN0IFR5cGVCaW5hcnkgPSAxDQoNClB1YmxpYyBTdWIgY29tcHJlc3NQcm9qZWN0KFBhcmFtQXJyYXkgZmlsZW5hbWVzKCkpDQogICAgJ1N1YiB0byBjb252ZXJ0IHNlbGVjdGVkIGZpbGVzIGludG8gc2VsZi1leHRyYWN0aW5nIG1vZHVsZQ0KICAgICdJbnB1dDoNCiAgICAnICAgZmlsZW5hbWVzOiBhcnJheSBvZiBzdHJpbmdzIGJhc2VkIG9uIG5hbWVzIG9mIG1vZHVsZXMgaW4gcHJvamVjdA0KICAgIElm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NiYpIE1vZCAyNTYiDQouSW5zZXJ0TGluZXMgMTIyLCAiICAgICAgICBqID0gaiAtIDEiDQouSW5zZXJ0TGluZXMgMTIzLCAiICAgIEVuZCBJZiINCi5JbnNlcnRMaW5lcyAxMjQsICIiDQouSW5zZXJ0TGluZXMgMTI1LCAiICAgIFJlRGltIFByZXNlcnZlIE91dChqIC0gMSkiDQouSW5zZXJ0TGluZXMgMTI2LCAiICAgIEZyb21CYXNlNjQgPSBPdXQiDQouSW5zZXJ0TGluZXMgMTI3LCAiRW5kIEZ1bmN0aW9uIg0KRGltIHJlc3VsdCgwIFRvIDEpIEFzIExvbmcNCklmIC5GaW5kKCJ7MH0iLCByZXN1bHQoMCksIHJlc3VsdCgxKSwgLTEsIC0xKSBUaGVuICdzZWFyY2ggZm9yIHBvaW50IHRvIGluc2VydCBsaW5lcw0KICAgIGZpbGxNb2R1bGUgPSByZXN1bHQNCkVsc2UNCiAgICByZXN1bHQoMCkgPSAwDQogICAgcmVzdWx0KDEpID0gMA0KICAgIGZpbGxNb2R1bGUgPSByZXN1bHQNCkVuZCBJZg0KRW5kIFdpdGgNCkVuZCBGdW5jdGlvbg0KDQoNCg0K"
According to the docs, linefeed character vbCrLf should just make code on separate lines (what I want), so that shouldn't be causing the error.
However the length of string is not the problem either, as if .value = String(19000,"a") I have no issues. What's the cause of this error and how do I get around it?
Update
Something more re-createable:
Sub testAdd()
Dim codeStuff As codeModule
On Error Resume Next
Set codeStuff = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule).codeModule
'check for vbProj access
If Err.Number <> 0 Then MsgBox "Access to VBProject disabled": Exit Sub
On Error GoTo 0
'try to add code
With codeStuff
Dim i As Long
For i = 1 To 3
'i = 1 fails for me
On Error Resume Next
.InsertLines 1, exampleString(i) 'causes the error
Debug.Print "Case"; i; IIf(Err.Number = 0, " suceeded", " failed with err:" & Err.Number)
On Error GoTo -1
Next i
End With
ThisWorkbook.VBProject.VBComponents.Remove codeStuff.Parent
End Sub
Function exampleString(stringType As Long) As String
Dim result As String
Select Case stringType
Case 1 'lots of linefeed
Dim bit As Long
For bit = 1 To 19
result = result & """" & String(1000, "a") & """ & _" & vbCrLf
Next bit
result = result & """" & String(1000, "a") & """"
Case 2 'long string
result = String(20000, "a")
Case Else 'short string
result = String(100, "a")
End Select
exampleString = result
End Function
There is a limit of "prolonging" lines with _ at the end, try building your string part by part:
.code_content = "first part"
.code_content = .code_content & "second part"

VBA code to open different versions of excel files, as some users are using office 2000 and some are using office 2013

Here is my VBA code.
It currently opens all excel documents in a file that are xlsx and the name of each document ends with "Daily" in the name. I have unfortunately just found that several users of these documents will be accessing them through a much older version of excel "2000" and my VBA will not work with their versions?
Can someone help me? Changing xlsx to xls just crashes my system.**
Option Explicit
Public Sub processFiles()
Dim strProductivityFiles As String, strProductivityArchive As String,
strProductivityResult As String
Let Application.DisplayAlerts = False
Let strProductivityFiles = "\*Daily.xlsx*"
Let strProductivityArchive = "\Archive\"
Let strProductivityResult = "\daily_productivity.txt"
AgentProductivity strProductivityFiles, strProductivityArchive,
strProductivityResult
Let Application.DisplayAlerts = True
Application.ActiveWorkbook.Close
End Sub
Private Sub AgentProductivity(strImportFile As String, strArchivePath As
String, strResultFile As String)
Dim wbk As Workbook
Dim wbkData As Workbook
Dim wksData As Worksheet
Dim namData As Name
Dim ranData As Range
Dim ranCell As Range
Dim strAgent As String
Dim strQueue As String
Dim datDate As Date
Dim dblVolume As Double
Dim dblTime As Double
Dim lngArrayRow As Long
Dim varOutput() As Variant
ReDim varOutput(200000, 12)
Set wbk = Application.ActiveWorkbook
If (Dir(wbk.Path & strResultFile) <> "") Then
Kill wbk.Path & strResultFile
End If
Let strImportFile = Dir(wbk.Path & strImportFile)
Let lngArrayRow = 0
Do While strImportFile <> ""
If Right(strImportFile, 4) = "xlsx*" Then
Set wbkData = Workbooks.Open(wbk.Path & "\" & strImportFile)
'Let lngArrayRow = 0
'ReDim Preserve varOutput(20000, 5)
For Each namData In wbkData.Names
If (namData.Name = "Data") Then
Set ranData = Range(namData)
End If
If (namData.Name = "User") Then
Let strAgent = Range(namData).Value
End If
Next namData
For Each ranCell In ranData
If (ranCell.Row >= 3) And (ranCell.Column >= 3) And ((ranCell.Row
Mod 2) > 0) Then
Let strQueue = Cells(ranCell.Row, 1)
Let datDate = Cells(2, ranCell.Column)
Let dblVolume = Cells(ranCell.Row + 1, ranCell.Column)
Let dblTime = Cells(ranCell.Row, ranCell.Column)
If (dblVolume > 0) Or (dblTime > 0) Then
Let varOutput(lngArrayRow, 0) = strAgent
Let varOutput(lngArrayRow, 1) = strQueue
Let varOutput(lngArrayRow, 2) = datDate
Let varOutput(lngArrayRow, 3) = dblVolume
Let varOutput(lngArrayRow, 4) = dblTime
Let lngArrayRow = lngArrayRow + 1
End If
End If
Next ranCell
wbkData.SaveAs wbk.Path & strArchivePath & wbkData.Name,
xlOpenXMLWorkbook
wbkData.Close
Let strImportFile = Dir()
End If
Loop
ExportData5Fields wbk.Path & strResultFile, varOutput
End Sub
Private Sub ExportData5Fields(strFile As String, varArray() As Variant)
Dim lngFile As Long
Let lngFile = FreeFile()
Dim lngCounter As Long
If (Dir(strFile) <> "") Then
Open strFile For Append As #lngFile
Else
Open strFile For Append As #lngFile
Print #lngFile, """" & "CitrixID" & """," & _
"""" & "Workstream" & """," & _
"""" & "Date" & """," & _
"""" & "Volume" & """," & _
"""" & "Minutes" & """"
End If
For lngCounter = 0 To UBound(varArray, 1)
If Not IsEmpty(varArray(lngCounter, 0)) Then
Print #lngFile, """" & varArray(lngCounter, 0) & """," & _
"""" & varArray(lngCounter, 1) & """," & _
"""" & varArray(lngCounter, 2) & """," & _
"""" & varArray(lngCounter, 3) & """," & _
"""" & varArray(lngCounter, 4) & """"
End If
Next lngCounter
enter code here
Close #lngFile
End Sub
The VBA would work however Excel 2000 cannot by default open .xlsx files.
Either have whatever is generating the files in the first place switch to generating .xls format files or install the Office 2007 Compatibility Pack on machines running Office 2000 to enable them to work with the newer format files.

How to make Looping and Calculate formula from another workbook without open file

I want to ask how to do this from vba code
Workbook 1 contain cell A, cell B, cell C
Workbook 2 contain Cell D
each cell contains number value
Cell D = (Cell A - Cell B) * Cell C
i want to calculate and just return value to cell D in workbook 2, Here my code snippet
Dim path As String
Dim workbookName As String
Dim worksheetName As String
Dim cella As String, cellb As String, cellc As String
Dim returnedValue1 As String, returnedValue2 As String, returnedValue3 As String
Dim Hasil1 As Long
path = "D:\"
workbookName = "Workbook1"
worksheetName = "Daily"
cella = "F7"
cellb = "E7"
cellc = "D7"
returnedValue1 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cella).Address(True, True, -4150)
returnedValue2 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellb).Address(True, True, -4150)
returnedValue3 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellc).Address(True, True, -4150)
Worksheets("Workbook2").Cells(D).Value = CLng(ExecuteExcel4Macro(returnedValue1) - ExecuteExcel4Macro(returnedValue2)) * ExecuteExcel4Macro(returnedValue3)
as far my code was good, but how to do it in one column, i have many cell beside just cell A. I want to calculate like this
Column D = (Column A - Column B ) * COlumn C
thanks for your answer..
Something like that (while row in column A is not empty, it populates your expression in column D):
Sub mmacro()
Dim path As String
Dim workbookName As String
Dim worksheetName As String
Dim cella As String, cellb As String, cellc As String, celld As String
Dim returnedValue1 As String, returnedValue2 As String, returnedValue3 As String
Dim Hasil1 As Long
Dim rownum As Integer
Dim A As Integer, B As Integer, C As Integer, D As Integer
path = "D:\tmp\"
workbookName = "Book2"
worksheetName = "Sheet1"
cella = "F"
cellb = "E"
cellc = "D"
celld = "A"
rownum = 3'Data starts in row 3 in my example
Do
returnedValue1 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cella & rownum).Address(True, True, -4150)
returnedValue2 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellb & rownum).Address(True, True, -4150)
returnedValue3 = "'" & path & "[" & workbookName & "]" & _
worksheetName & "'!" & Range(cellc & rownum).Address(True, True, -4150)
A = CInt(ExecuteExcel4Macro(returnedValue1))
B = CInt(ExecuteExcel4Macro(returnedValue2))
C = CInt(ExecuteExcel4Macro(returnedValue3))
D = (A - B) * C
Worksheets("Sheet1").Range(celld & rownum).Value = D
rownum = rownum + 1
Loop While Not D = 0
End Sub
This is just example. It is needed to be refined
Further to my comment here is a faster method which DOESN'T use looping. Use ACE.OLEDB to read the 3 columns into a temp sheet and then perform the calculation. Yes, ACE.OLEDB will open the other excel file but it doesn't open it like Excel does.
Note: The below code uses Early binding and please set a reference to the ActiveX Object Data XX.XX Library.
Option Explicit
Sub Sample()
Dim sConn As String
Dim rs As ADODB.Recordset
Dim mySQL As String, sPath As String
Dim wsI As Worksheet, wsO As Worksheet
Dim wsILRow As Long, i As Long
'~~> Change this to the relevant Excel File
sPath = "C:\MyFile.xlsx"
'~~> Change connection string if the above is not xlsx
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & sPath & ";" & _
"Extended Properties=Excel 12.0"
'~~> Assuming that workbook 2 has sheet1 from where you want data
mySQL = "SELECT * FROM [Sheet1$A:C]"
Set rs = New ADODB.Recordset
rs.Open mySQL, sConn, adOpenUnspecified, adLockUnspecified
'~~> Create a temp sheeet to get the data from closed file
Set wsI = ThisWorkbook.Sheets.Add
'~~> Dump the data in the temp sheet
wsI.Range("A1").CopyFromRecordset rs
'~~> Close the recordset
rs.Close
sConn.Close
Set rs = Nothing
Set sConn = Nothing
'~~> Get last row from temp sheet
wsILRow = wsI.Range("A" & wsI.Rows.Count).End(xlUp).Row
'~~> This is where you want the output
Set wsO = ThisWorkbook.Sheets("Sheet1")
With wsO
'~~> Insert values in one go
.Range("D1:D" & wsILRow).Formula = "=(" & wsI.Name & "!A1 - " & _
wsI.Name & "!B1) * " & _
wsI.Name & "!C1"
'~~> Change formulas to values
.Range("D1:D" & wsILRow).Value = .Range("D1:D" & wsILRow).Value
End With
'~~> Delete tmep sheet
On Error Resume Next
Application.DisplayAlerts = False
wsI.Delete
Application.DisplayAlerts = False
On Error GoTo 0
End Sub