I am writing an automation script as I have a need to run a report on 16 separate split skills each day for a period of 6 months. The script works, with one problem. It will run 63 iterations (i.e. 3 days at 16 = 48 + 15 = 63). After the 15th loop (63rd overall iteration) it will give an error: "microsoft excel is waiting for another application to complete an OLE action" It would appear to me, though I could very easily be wrong, that either I am overloading a variable or possibly not fully closing something on the CMS side. The fact that it is the 63rd iteration (64-1) seems awfully suspicious, but I am not sure what I could be overloading as far as variables going. I don't have any 8-bit variables (unless I am missing something). Also, I should point out that after running the macro, I am uanble to log back into the CMS app manually without restarting, so my hunch is that I am not fully closing something and that maybe there is a limit on the number of instances allowed in CMS. I included the script below, except that the names of the skills, server address, username and password have been removed for security reasons. Any help would be greatly appreciated.
Public Sub Single_CMS_Report_Extract()
On Error Resume Next
' Add the files specified below to the References section:
' Tools -> References -> Browse to the CMS directory,
' e.g.: "C:\Program Files\Avaya\CMS Supervisor R14"
Dim cmsApplication As ACSUP.cvsApplication 'acsApp.exe
Dim cmsServer As ACSUPSRV.cvsServer 'acsSRV.exe
Dim cmsConnection As ACSCN.cvsConnection 'cvsconn.dll
Dim cmsCatalog As ACSCTLG.cvsCatalog 'cvsctlg.dll
Dim cmsReport As Object 'ACSREP.cvsReport 'acsRep.exe
Dim myLog As String, myPass As String, myServer As String
Dim reportPath As String, reportName As String, reportPrompt(1 To 2, 1 To 3) As String
Dim exportPath As String, exportName As String
Dim StartRunTime, EndRunTime As Date
Dim DayToRun, EndDate As Date
Dim Skill(1 To 16) As String
MsgBox ("Please ensure CMS open and logged in prior to continuing")
StartRunTime = Now
'Start Date
DayToRun = "12/16/2015"
'End Date
EndDate = "12/21/2015"
Skill(1) = "XXXXXXXX"
Skill(2) = "XXXXXXXX"
Skill(3) = "XXXXXXXX"
Skill(4) = "XXXXXXXX"
Skill(5) = "XXXXXXXX"
Skill(6) = "XXXXXXXX"
Skill(7) = "XXXXXXXX"
Skill(8) = "XXXXXXXX"
Skill(9) = "XXXXXXXX"
Skill(10) = "XXXXXXXX"
Skill(11) = "XXXXXXXX"
Skill(12) = "XXXXXXXX"
Skill(13) = "XXXXXXXX"
Skill(14) = "XXXXXXXX"
Skill(15) = "XXXXXXXX"
Skill(16) = "XXXXXXXX"
While DayToRun < (EndDate + 1)
For i = 1 To 16
' Assigns Variables
myLog = "myuser"
myPass = "mypass"
myServer = "xx.xx.xx.xx"
'reportPath is the tab and "Category" that the report is found in Avaya
reportPath = "Historical\Split/Skill\"
reportName = "Summary Interval"
'list of input names requested.....
reportPrompt(1, 1) = "Split/Skill"
reportPrompt(1, 2) = "Date"
reportPrompt(1, 3) = "Times"
'list of responses being used for input
reportPrompt(2, 1) = Skill(i)
reportPrompt(2, 2) = DayToRun
reportPrompt(2, 3) = "00:00-23:30"
'path and name of exported report file
exportPath = "H:\Avaya data\"
If i <> 5 Then
exportName = Month(DayToRun) & "-" & Day(DayToRun) & "-" & Skill(i) & ".csv"
Else
exportName = Month(DayToRun) & "-" & Day(DayToRun) & "- DL-Toll Free" & ".csv"
End If
' Open the CMS Application, launches acsApp.exe
' If a CMS Supervisor console is already open,
' the existing acsApp.exe is used.
Set cmsApplication = CreateObject("ACSUP.cvsApplication")
Set cmsServer = CreateObject("ACSUPSRV.cvsServer")
Set cmsConnection = CreateObject("ACSCN.cvsConnection")
cmsConnection.bAutoRetry = True
' Connetsc to the server, launches acsSRV.exe & ACSTrans.exe (2x)
If cmsApplication.CreateServer(myLog, myPass, "", myServer, False, "ENU", cmsServer, cmsConnection) Then
If cmsConnection.login(myLog, myPass, myServer, "ENU", "", False) Then
End If
End If
' Gets collection of Reports available on cmsServer
Set cmsCatalog = cmsServer.Reports
If cmsServer.Connected = False Then cmsServer.Reports.ACD = 1
' Sets parameters for report, launches ACSRep.exe (2x)
cmsCatalog.CreateReport cmsCatalog.Reports.Item(reportPath & reportName), cmsReport
If cmsReport.SetProperty(reportPrompt(1, 1), reportPrompt(2, 1)) And cmsReport.SetProperty(reportPrompt(1, 2), reportPrompt(2, 2)) And cmsReport.SetProperty(reportPrompt(1, 3), reportPrompt(2, 3)) Then
End If
' Runs report and extracts results --- the 44 is the field delimiter
cmsReport.ExportData exportPath & exportName, 44, 0, False, False, True
' Kills active report & server
If Not cmsServer.Interactive Then
cmsServer.ActiveTasks.Remove cmsReport.TaskID
cmsApplication.Servers.Remove cmsServer.ServerKey
End If
' Logs out
cmsReport.Quit
cmsConnection.Logout
cmsConnection.Disconnect
cmsServer.Connected = False
' Releases objects
Set cmsReport = Nothing
Set cmsCatalog = Nothing
Set cmsConnection = Nothing
Set cmsServer = Nothing
Set cmsApplication = Nothing
Next
i = Nothing
DayToRun = DateAdd("d", 1, DayToRun)
Wend
EndRunTime = Now
MsgBox ("Run-time = " & Minute(EndRunTime - StartRunTime) & ":" & Second(EndRunTime - StartRunTime))
End Sub
Related
I've got a really odd case… hopefully someone is able to help me out, I've search many forums looking for a solution, the closest I could find related to it (kinda) is here, though I've tried all the suggestions to no avail…
I'm trying to run a function to return a data list in a string delimitated by a semicolon from an oracle stored function. (This value function call seems to work fine).
I then loop through the string for each data value and print it to a blank table (0 rows) declared in my subroutine. which I use to load into an access data base. (just trust it make sense in the big picture…).
The issue, fundamentally is that no information is printed into the table. However when I step through the code it works fine.
After troubleshooting I THINK (see my test scenarios below code) the issue comes up after the listrows.add line... though not obviously.
I don't think this line is executed by the time the first value is trying to print to the table.
The most confusing part is I'm running through 2 nearly identical procedures (call function -> Return value -> print values to table) immediately before this portion of the code and they work without fail.
Code Excerpt:
'run function to get string ... this works
DoEvents ' not in original design
RelRtnStr = Prnt(Cat, "A Third Oracle Function Name")
DoEvents ' not in original design
RelChopVar = RelRtnStr
StrFldCnt = 0
Checking = True ''' CodeBreak Test 1
DoEvents ' not in original design
AppendRlLmTbl.ListRows.Add ''''''''This isn't appearing to work...
DoEvents ' not in original design
Debug.Print Now ' not in original design
Application.Wait (Now + TimeValue("0:00:3")) ' not in original design
Debug.Print Now ' not in original design
While StrFldCnt < 80 And (Len(RelChopVar) - Len(Replace(RelChopVar, ";", ""))) > 0 And Checking
'## Count String Position
StrFldCnt = StrFldCnt + 1
'## Find Current String Value & Remainder String
If InStr(RelChopVar, ";") <> 0 Then
'Multiple Values Left
FldVal = Replace(Left(RelChopVar, InStr(RelChopVar, ";")), ";", "")
RelChopVar = Right(RelChopVar, Len(RelChopVar) - InStr(RelChopVar, ";"))
Else
'Last Value
FldVal = RelChopVar
Checking = False
End If
'## Get Field Name For Current Value & Print to Table
FldNm = CStr(RefRtrn(2, CStr(StrFldCnt))) ''' CodeBreak Test 2
AppendRlLmTbl.ListColumns(FldNm).DataBodyRange.Value = FldVal '''CodeBreak 2 error thrown
Debug.Print StrFldCnt & FldNm & FldVal
Wend
AppendRlLmTbl.ListColumns("Catalogue").DataBodyRange.Value = Cat
So far I've tested a ton of options suggested online, not necessarily understanding each test... This is what I've gleaned.
If I step through the code, it works
If I set a breakpoint at "CodeBreak Test 1" and "F5" the rest, it works …
If I set a breakpoint at "CodeBreak Test 2" I get an "Object with variable not set" error thrown …
Things I've tried …
Wrapping anything and everything with DoEvents
setting a wait time after the listObjects.add row
Validated the code performs the While loop when running the "full procured" (as opposed to stepping through)
The worst part, I have no idea why the object won't declare properly when setting a break point after the add row line but sets properly when break point is set before and has no error thrown when running the full procedure (I have no on error declarations.)...
It of course must be related in my mind but I can't find any information online and unfortunately have no formal VBA background and 1 undergrad course as a programming background in general. Aka I'm out of my depth and super frustrated.
PS. first post, so please be nice :p
Full Code Below:
Option Explicit
'## Here's my attempt to clean up and standardize the flow
'## Declare my public variables
' WorkBook
Public WB As Workbook
' Sheets
Public Req2ByWS As Worksheet
Public ReqSpecsWS As Worksheet
Public ReqInstrcWS As Worksheet
Public ConfigReqWS As Worksheet
Public AppendReqWS As Worksheet
Public AppendRlLmWS As Worksheet
' Objects (tables)
Public ReqConfigTbl As ListObject
Public SpecConfigTbl As ListObject
Public CurrRegIDTbl As ListObject
Public AppendReqTbl As ListObject
Public AppendRlLmTbl As ListObject
'## ##
'## Get Data from Tom's Functions ##
Sub GetSpotBuyData()
'## Preliminary Config ##
'## Turn OFF Warnings & Screen Updates
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'## Set global Referances to be used in routine
' WorkBooks
Set WB = Workbooks("MyWb.xlsm")
' WorkSheets
Set Req2ByWS = WB.Sheets("MyWb Pg1")
Set ReqSpecsWS = WB.Sheets("MyWb Pg2")
Set ConfigReqWS = WB.Sheets("MyWb Pg3")
Set AppendReqWS = WB.Sheets("MyWb Pg4")
Set AppendRlLmWS = WB.Sheets("MyWb Pg5")
' Tables
Set ReqConfigTbl = ConfigReqWS.ListObjects("MyWS Tbl1")
Set SpecConfigTbl = ConfigReqWS.ListObjects("MyWS Tbl2")
Set CurrRegIDTbl = ConfigReqWS.ListObjects("MyWS Tbl3")
Set AppendReqTbl = AppendReqWS.ListObjects("MyWS Tbl4")
Set AppendRlLmTbl = AppendRlLmWS.ListObjects("MyWS Tbl5")
'## Declare Routine Specefic Variables
Dim Doit As Variant
Dim Checking As Boolean
Dim Cat As String
Dim CatRtnStr As String
Dim CatChopVar As String
Dim SpecRtnStr As String
Dim SpecChopVar As String
Dim RelRtnStr As String
Dim RelChopVar As String
Dim FldVal As String
Dim FldNm As String
Dim StrFldCnt As Integer
'## 1) General Set-Up ##
'## Unprotect tabs (loop through All Tabs Unprotect)
Doit = Protct(False, WB, "Mypassword")
'## Refresh Data
Doit = RunUpdateAl(WB)
'## 2) Find the Catalgue we are playing with ##
'## Grab Catalogue input from ISR
If [Catalogue].Value = "" Then
MsgBox ("Please Enter a Catalogue")
GoTo ExitSub
Else
Cat = [Catalogue].Value
End If
'## 3) Run Toms Function and print the results to the form & Append Table ##
'## 3a) Do it for Cat Info Function
'## Get Cat Info String From Function
CatRtnStr = Prnt(Cat, "An Oracle Functions Name")
CatChopVar = CatRtnStr
If CatChopVar = "No Info" Then
MsgBox ("No Info Found in Catalogue Data Search.")
GoTo SkipCatInfoPrint
End If
'## Loop Through Data String & Write to Form
StrFldCnt = 0
Checking = True
AppendReqTbl.ListRows.Add
While Checking
'## Count String Position
StrFldCnt = StrFldCnt + 1
'## Find Current String Value & Remainder String
If InStr(CatChopVar, ";") <> 0 Then
'Multiple Values Left
FldVal = Replace(Left(CatChopVar, InStr(CatChopVar, ";")), ";", "")
CatChopVar = Right(CatChopVar, Len(CatChopVar) - InStr(CatChopVar, ";"))
Else
'Last Value
FldVal = CatChopVar
Checking = False
End If
'## Get Field Name For Current Value & Print to Form
FldNm = CStr(RefRtrn(1, CStr(StrFldCnt)))
If FldNm <> "CustomerSpecification" And FldNm <> "ShiptoAddress" Then
'Take Value as is
Req2ByWS.Range(FldNm).Value = FldVal
AppendReqTbl.ListColumns(FldNm).DataBodyRange.Value = FldVal
ElseIf FldNm = "CustomerSpecification" Then
'Replace : with New Line
FldVal = Replace(FldVal, " : ", vbLf)
Req2ByWS.Range(FldNm).Value = FldVal
AppendReqTbl.ListColumns(FldNm).DataBodyRange.Value = FldVal
ElseIf FldNm = "ShiptoAddress" Then
'Replace - with New Line
FldVal = Replace(FldVal, " - ", vbLf)
Req2ByWS.Range(FldNm).Value = FldVal
AppendReqTbl.ListColumns(FldNm).DataBodyRange.Value = FldVal
End If
Wend
'## 3b) Do it for Spec Function
SkipCatInfoPrint:
'## Get Spec Info String From Function
SpecRtnStr = Prnt(Cat, "Another Oracle Functions Name")
SpecChopVar = SpecRtnStr
If SpecChopVar = "No Info" Then
MsgBox ("No Info Found in Data Search.")
GoTo SkipSpecInfoPrint
End If
'## Loop Through Data String & Write to Form
StrFldCnt = 0
Checking = True
While StrFldCnt < 80 And (Len(SpecChopVar) - Len(Replace(SpecChopVar, ";", ""))) > 0 And Checking
'## Count String Position
StrFldCnt = StrFldCnt + 1
'## Find Current String Value & Remainder String
If InStr(SpecChopVar, ";") <> 0 Then
'Multiple Values Left
FldVal = Replace(Left(SpecChopVar, InStr(SpecChopVar, ";")), ";", "")
SpecChopVar = Right(SpecChopVar, Len(SpecChopVar) - InStr(SpecChopVar, ";"))
Else
'Last Value
FldVal = SpecChopVar
Checking = False
End If
'## Get Field Name For Current Value & Print to Form
FldNm = CStr(RefRtrn(2, CStr(StrFldCnt)))
ReqSpecsWS.Range(FldNm).Value = FldVal
AppendReqTbl.ListColumns(FldNm).DataBodyRange.Value = FldVal
Wend
'## 3c) Do it for Rel Limits Function
SkipSpecInfoPrint:
'## Get Rel Limits String From Function
RelRtnStr = Prnt(Cat, "A Third Functions Name")
RelChopVar = RelRtnStr
If RelChopVar = "No Info" Then
MsgBox ("No Info Found in Data Search.")
GoTo ExitSub
End If
'## Loop Through Data String & Write to Form
StrFldCnt = 0
Checking = True
AppendRlLmTbl.ListRows.Add
While StrFldCnt < 80 And (Len(RelChopVar) - Len(Replace(RelChopVar, ";", ""))) > 0 And Checking
'## Count String Position
StrFldCnt = StrFldCnt + 1
'## Find Current String Value & Remainder String
If InStr(RelChopVar, ";") <> 0 Then
'Multiple Values Left
FldVal = Replace(Left(RelChopVar, InStr(RelChopVar, ";")), ";", "")
RelChopVar = Right(RelChopVar, Len(RelChopVar) - InStr(RelChopVar, ";"))
Else
'Last Value
FldVal = RelChopVar
Checking = False
End If
'## Get Field Name For Current Value & Print to Form
FldNm = CStr(RefRtrn(2, CStr(StrFldCnt)))
AppendRlLmTbl.ListColumns(FldNm).DataBodyRange.Value = FldVal
Wend
AppendRlLmTbl.ListColumns("SpecificFieldName").DataBodyRange.Value = Cat
'## 4) Re-Format and Clean Up Program ##
ExitSub:
'## Clean-Up Formatting
Req2ByWS.Range("F:F", "C:C").ColumnWidth = 30
Req2ByWS.UsedRange.Rows.AutoFit
Req2ByWS.UsedRange.Columns.AutoFit
Req2ByWS.Range("G:G").ColumnWidth = 15
Req2ByWS.Range("J:R").ColumnWidth = 12
Req2ByWS.Range("D:D").ColumnWidth = 12
'## Protect tabs (loop through All Tabs Protect)
'Doit = Protct(True, WB, "Mypassword", Req2ByWS.Name)
'Req2ByWS.Unprotect ("Mypassword")
'Application.Wait (Now + TimeValue("0:00:10"))
Req2ByWS.Select
'## Turn ON Warnings & Screen Updates
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I stupidly had an enable background refresh for that specific table. An early call to refresh all data triggered the refresh, code would execute and the refresh would finally complete shortly after the code finished executing... in break mode the refresh would complete prior too. Thanks PEH for helping me look into this.
I'm trying to call excel's FORECAST.ETS from VBA in my access project but it seems like no matter what I do I get this error:
"VBA Error 1004 Invalid number of arguments."
Here's what I'm doing -
'**********************************************
Public Sub testFCsof()
Dim testrfXL As Object
Dim testrfNowDate As Date
Dim testrfempSQLStr As String
Dim testrfempSQLRS As DAO.Recordset
Dim testrfRecNo As Integer
Dim testrfDateARRAY() As Date
Dim testrfPointsARRAY() As Double
Dim testrfFDFCAST As Double
Dim fdtestempID As Long
On Error GoTo Err_testrfNBA
Set todaysDB = CurrentDb()
fdtestempID = 382
testrfFDFCAST = 1000000
testrfempSQLStr = "SELECT NBAFANempPER.eventTime, NBAFANempPER.FDpoints " & _
"FROM NBAFANempPER WHERE ((NBAFANempPER.empID)= " & fdtestempID & ") ORDER BY NBAFANempPER.eventTime;"
Set testrfempSQLRS = todaysDB.OpenRecordset(testrfempSQLStr, dbOpenDynaset, dbSeeChanges, dbReadOnly)
If Not (testrfempSQLRS.BOF And testrfempSQLRS.EOF) Then 'only do this if we have records
testrfempSQLRS.MoveLast
ReDim testrfDateARRAY(testrfempSQLRS.RecordCount - 1)
ReDim testrfPointsARRAY(testrfempSQLRS.RecordCount - 1)
testrfempSQLRS.MoveFirst
testrfRecNo = 0
Do While Not testrfempSQLRS.EOF
testrfDateARRAY(testrfRecNo) = CDate(dateHeadFunk(CDate(testrfempSQLRS!eventTime)))
testrfPointsARRAY(testrfRecNo) = CDbl(testrfempSQLRS!FDpoints)
testrfRecNo = testrfRecNo + 1
testrfempSQLRS.MoveNext
Loop
Set testrfXL = CreateObject("Excel.Application")
testrfNowDate = Now()
testrfFDFCAST = testrfXL.WorksheetFunction.Forecast.ets(Arg1:=testrfNowDate, Arg2:=testrfPointsARRAY, Arg3:=testrfDateARRAY, Arg4:=0, Arg5:=1, Arg6:=5)
Set testrfXL = Nothing
End If
Exit_testrfNBA:
Erase testrfPointsARRAY
Erase testrfDateARRAY
testrfNowDate = Empty
testrfempSQLStr = ""
If Not testrfempSQLRS Is Nothing Then
testrfempSQLRS.Close
Set testrfempSQLRS = Nothing
End If
Exit Sub
Err_testrfNBA:
MsgBox "Got a sucky forecast number back.."
generic.TestODBCErr
Resume Exit_testrfNBA
End Sub
'**********************************************
The arrays fill up just fine, both the same size.
I can call other Excel functions without a problem.
Can't figure out what the problem could be. I've tried this with and without the "Arg=" tags, with and without the last three optional arguments, tried wrapping the arrays with Array(myArray), even set the Arrays to Variant.
At least in Excel VBA, the function name is Forecast_ETS, not Forecast.ETS.
I have a tool that capture screenshots of the application that we test at our workplace. Now once I complete my testing of a particular test case or scenarios, we attach the screenshot that we have taken to HP Quality Center manually.
I want to automate this and make my tool to upload the word document to a test in QC Test Lab. Is this possible? If Yes, How can we do this in Excel VBA?
Operations that we need to perform would be as below:
Connect to QC project with login credentials, domain & project details
Pick a file(s) from a local folder
Upload a file(s) to QC Test Lab, specific test case
I used the below code, but getting error in that code. I marked it in the code below, please check below :
Dim intTestID, FldPath, TestSetName, i
Dim TestSetFact, tsTreeMgr, tSetFolder, TestSetsList, theTestSet
Dim TestSetIdentifier, TSTestFact, TestSetTestsList, testInstanceF, aFilter
Dim lst, tstInstance
intTestID = "8968"
FldPath = TextBox3.Text '"Root\ProjFold\Release1\BRD"
TestSetName = ComboBox3.Text '"BRD" '
Set Connection = CreateObject("TDApiOle80.TDConnection")
Connection.InitConnectionEx Sheet2.Range("B1").Value2
Connection.Login TextBox1.Text, TextBox2.Text
Connection.Connect ComboBox1.Text, ComboBox2.Text
Set TestSetFact = Connection.TestSetFactory
Set tsTreeMgr = Connection.TestSetTreeManager
Set tSetFolder = tsTreeMgr.NodeByPath(FldPath)
Set TestSetsList = tSetFolder.FindTestSets(TestSetName)
Set theTestSet = TestSetsList.Item(1)
TestSetIdentifier = theTestSet.ID
i = 0
Set TSTestFact = theTestSet.TSTestFactory
Set TestSetTestsList = TSTestFact.NewList("")
Set testInstanceF = Connection.TSTestFactory
Set aFilter = testInstanceF.Filter
aFilter.Filter("TC_TEST_ID") = intTestID
Set lst = testInstanceF.NewList(aFilter.Text)
Set tstInstance = lst.Item(1) <---------------- getting error here
MsgBox (tstInstance.Field("TS_Name"))
'tstInstance.Status = "Failed"
'tstInstance.Field("TC_STATUS") = Item1.Status '"Passed"
'tstInstance.Post
Dim RunF, runName, NewRun, runStepF, runlst, Item1, runStep2
MsgBox (tstInstance.Field("TS_Subject"))
Set RunF = tstInstance.RunFactory
runName = "Run_" & Month(Date) & "-" & Day(Date) & "_" & Hour(Now) & "-" & Minute(Now) & "-" & Second(Now)
Set NewRun = RunF.AddItem(Null)
NewRun.Status = "Passed"
NewRun.Name = runName
NewRun.Post
NewRun.CopyDesignSteps
NewRun.Post
Set runStepF = NewRun.StepFactory
Set runlst = runStepF.NewList("")
For Each Item1 In runlst
Set runStep2 = Item1
runStep2.Status = "Passed" '
runStep2.Field("ST_ACTUAL") = "As Expected"
runStep2.Post
Next
'tstInstance.Refresh
tstInstance.Status = "Failed"
tstInstance.Post
Connection.DisconnectProject
Connection.ReleaseConnection
'Set QC = Nothing
Set Connection = Nothing
The error is occurring because the array of objects is not returning. You need to check if the Filter gives you a list of results before assuming that lst.Item(1) exists.
For instance:
If lst.Count > 0 Then Set tstInstance = lst.Item(1)
I'm writing in VB 2010 with a form with one button to be completely idiot. I haven't done VB in awhile and noticed 2010 has a lot of changes compare when I did it a couple of years ago.
What I need done is it to read from a file and write two new separate files while writing to original. It will read from a text file to get some contents and compare the current date.
The text content will be a serial and the next two columns will be dates.
Dim iFileName As New StreamReader("G:\SAP In and Out\test.txt", False)
Dim sFileExport As New StreamWriter(DateValue(Now)) + " SAP Export", False)
Dim sFileImport As New StreamWriter(DateAdd(DateInterval.Day, 10, DateValue(Now)) + " SAP Import", False)
Dim VTS As String 'Will be used to grab the VT serial
Dim CurrentDate As Date 'Will be used to compare to grabbed dates
Dim NextDateOut As Date 'Will be used to grab next date out value
Dim NextDateIn As Date 'Will be used to grab next date in value
'Setting a consistant value with daily'
CurrentDate = DateValue(Now)
Do While Not EOF(1)
Input(iFileName),VTS,NextDateOut,NextDateIn
If CurrentDate = NextDateOut Then
'Write to the export File
sFileExport.write(VTS)
'Write under the just read line in the open file
iFileName.write(/newline + VTS + /TAB + (DateAdd(DateInterval.Day, 20, DateValue(Now)) + /tab + (DateAdd(DateInterval.Day, 30, DateValue(Now)))
ElseIf CurrentDate = NextDateIn Then
'Write to import file
sFileImport.Write(VTS)
End If
Loop
End Sub
But my syntax is off and it's obviously not running since I'm asking for help.
Please help and thanks in advance. I've been working on this for hours and haven't had any positive results yet.
Well I think its right now, but i had to add an extra function so i could test it out.
I was receiving errors o the date format because I expect you use US date format (MM/DD/YYYY) and I use UK date format (DD/MM/YYYY).
Anyway you can strip the function out as I dont think you will need it, but I've left it in anyway so you can see whats going on its quite self explanatory and simply converts between the date formats, though it was made more difficult by the fact your days and month are not two digits long (no leading zero).
I hope it helps point you in the right direction and you can chop and change it to your preference.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim iFileName As New System.IO.StreamReader("c:\temp\vttest.txt", False)
Dim iReadData As List(Of String)
Dim Buffer As String
'Read complete file into array
iReadData = New List(Of String)
Do While Not iFileName.EndOfStream()
Try
Buffer = ""
Buffer = iFileName.ReadLine()
iReadData.Add(Buffer)
Catch ex As Exception
'error or end of file
End Try
Loop
iFileName.Close()
'Not needed
'Dim VTS As String 'This is in iLineData(0) after we split the line
'Dim NextDateOut As Date 'This is in iLineData(1) after we split the line
'Dim NextDateIn As Date 'This is in iLineData(2) after we split the line
'Process
Dim iFileUpdated As New System.IO.StreamWriter("c:\temp\vttest_copy.txt", True)
Dim sFileExport As New System.IO.StreamWriter("c:\temp\vttest" & Replace(DateValue(Now), "/", "_") & " SAP Export.txt", True)
Dim sFileImport As New System.IO.StreamWriter("c:\temp\vttest" & Replace(DateAdd(DateInterval.Day, 10, DateValue(Now)), "/", "_") + " SAP Import.txt", True)
Dim iLineData() As String
'Setting a consistant value with daily'
Dim CurrentDate As Date = DateValue(Now)
Dim RowId = 0
Do While RowId < iReadData.Count()
iLineData = Split(iReadData(RowId), " ")
iFileUpdated.WriteLine(iLineData(0) & " " & iLineData(1) & " " & iLineData(2))
If CurrentDate = FormatDate(iLineData(1), "US", "UK") Then
'Write to the export File
sFileExport.WriteLine(iLineData(0))
'Write under the just read line in the open file
iFileUpdated.WriteLine(iLineData(0) & " " & (DateAdd(DateInterval.Day, 20, DateValue(Now))) & " " & (DateAdd(DateInterval.Day, 30, DateValue(Now))))
ElseIf CurrentDate = FormatDate(iLineData(2), "US", "UK") Then
'Write to import file
sFileImport.WriteLine(iLineData(0))
End If
RowId = RowId + 1
Loop
sFileExport.Close()
sFileImport.Close()
iFileUpdated.Close()
MsgBox("Finshed")
End Sub
'This section added because my PC is set to DD/MM/YYYY (UK)
'Expect yours is set to MM/DD/YYYY (US)
Function FormatDate(ThisDate As String, ThisFormat As String, ThisTargetFormat As String) As Date
Dim X As Integer = 0
Dim Day1 As Integer = 0
Dim Month1 As Integer = 0
Dim Year1 As Integer = 0
Dim Buf As String = ""
If ThisFormat = "US" Then
For X = 1 To Len(ThisDate)
If Mid(ThisDate, X, 1) = "/" Then
If Month1 > 0 Then
Day1 = Buf
Buf = ""
Else
Month1 = Buf
Buf = ""
End If
Else
Buf = Buf & Mid(ThisDate, X, 1)
End If
Next
Year1 = Buf
Else
For X = 1 To Len(ThisDate)
If Mid(ThisDate, X, 1) = "/" Then
If Day1 > 0 Then
Month1 = Buf
Buf = ""
Else
Day1 = Buf
Buf = ""
End If
Else
Buf = Buf & Mid(ThisDate, X, 1)
End If
Next
Year1 = Buf
End If
'reformat for output
If ThisFormat = "US" Then
If ThisTargetFormat = "US" Then
'USA
FormatDate = (Format(Month1, "00") & "/" & Format(Day1, "00") & "/" & Format(Year1, "0000"))
Else
'UK
FormatDate = (Format(Day1, "00") & "/" & Format(Month1, "00") & "/" & Format(Year1, "0000"))
End If
Else
If ThisTargetFormat = "US" Then
'USA
FormatDate = (Format(Month1, "00") & "/" & Format(Day1, "00") & "/" & Format(Year1, "0000"))
Else
'UK
FormatDate = (Format(Day1, "00") & "/" & Format(Month1, "00") & "/" & Format(Year1, "0000"))
End If
End If
End Function
Additionally i changed the file names so as not to overwrite the existing files (So i could compare the two files).
Most of the problems were arising from the back slashes in the dates in the FILENAMES - making the pc look for paths like /3/12 i guess it was translating the slashes into folder delimiters so I replaced them with UNDERSCORES on the fly.
Once you have edited the code to your preference you can OVERWRITE the existing file rather than generating a _copy.txt as thats how I tested with a _copy.txt in the sample.
Update
Thanks for the feedback. Well its strange that your (generated) files are empty, because in the ones I have ONE has data the other is empty. This leads me to the assumption that your tweaks may have something to do with it?
For your reference I have posted them below.
ORIGINAL FILE [VTSTEST.TXT]
VT1000 3/26/2013 4/5/2013
VT1100 3/26/2013 4/5/2013
VT2000 3/27/2013 4/6/2013
VT2200 3/27/2013 4/6/2013
COPY OF VTSTEST.TXT (after modification)
VT1000 3/26/2013 4/5/2013
VT1100 3/26/2013 4/5/2013
VT2000 3/27/2013 4/6/2013
VT2000 16/04/2013 26/04/2013
VT2200 3/27/2013 4/6/2013
VT2200 16/04/2013 26/04/2013
Note: I expect the two longer lines are the ones inserted inbetween the existing four lines of text
VTTEST06_04_2013 SAP Import.Txt
This file was empty
VTTEST27_03_2013 SAP Export.TXT
VT2000
VT2000
I wrote a bar code program sometime ago with vb.net that when the end user clicks the print button, the program will open the text file that contains the ZPL bar code, increment the serial number by 1, write the new serial number back to the text file, and then print out the predetermined amount of bar codes to a zebra printer.
Now I am trying to rewrite the code so that it will print the number of bar codes the end user wants from the number they type into the PrintDialog. In my updated code, I tried putting in a DO UNTIL ......LOOP. It will print out the number of bar codes the user puts into the PrintDialog box, but it doesn't serialize. By that I mean if the user enters 5 into the PrintDialog, the program will print serial # 01 five times instead of printing 02, 03, 04, 05, 06.
Can anyone give me some pointers on how to have the program read, write, and print the desired x amount of times based on the number a user inputs into the PrintDialog?
Here is my original code:
Dim sL() As String = IO.File.ReadAllLines("C:\Labels\loop test.txt")
Dim CurrentBar(2) As String
For i = 0 To 2
CurrentBar(i) = sL(sL.Length - 3 + i)
Next
If CurrentBar(1).Length >= 28 Then
CurrentBar(1) = CurrentBar(1).Substring(0, 18) & Format(CInt(CurrentBar(1).Substring(18, 10) + 1), "0000000000") & CurrentBar(1).Substring(28)
Else
MessageBox.Show("String is not long enough!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Write the updated vaules back to the Text File
IO.File.WriteAllText("C:\Labels\loop test.txt",
CurrentBar(0) & vbNewLine &
CurrentBar(1) & vbNewLine &
CurrentBar(2))
Dim psi As New ProcessStartInfo
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = "C:\Labels\loop test.txt"
Process.Start(psi)
And here is my updated code:
Dim PrintDialog1 As New PrintDialog()
Dim psi As New ProcessStartInfo
Dim sL() As String = IO.File.ReadAllLines("C:\Labels\loop test.txt")
Dim CurrentBar(2) As String
Do Until PrintDialog1.PrinterSettings.Copies - 1
For i = 0 To 2
CurrentBar(i) = sL(sL.Length - 3 + i)
Next
If CurrentBar(1).Length >= 28 Then
CurrentBar(1) = CurrentBar(1).Substring(0, 18) & Format(CInt(CurrentBar(1).Substring(18, 10) + 1), "0000000000") & CurrentBar(1).Substring(28)
Else
MessageBox.Show("String is not long enough!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Write the updated vaules back to the Text File
IO.File.WriteAllText("C:\Labels\loop test.txt",
CurrentBar(0) & vbNewLine &
CurrentBar(1) & vbNewLine &
CurrentBar(2))
'Print the labels
'Get the number of copies to print
If (PrintDialog1.ShowDialog() = DialogResult.OK) Then
'print desired number of copies to target printer
For I = 0 To PrintDialog1.PrinterSettings.Copies - 1
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
psi.FileName = "C:\Labels\loop test.txt"
Process.Start(psi)
Next
End If
Loop
And here is my text file:
^XA
^LH20,85^BY3^AE^SN0000000001R,,Y^B3N,,60,,Y^FS
^XZ
I think your problem in your new code is that you are reading in the text file before you do the loop. At the end of the loop, you write out the new values, but never read them back in (or reuse them). Therefore, the input is always going to be what it was before the loop iterates. I think by putting
sl() = IO.File.ReadAllLines("C:\Labels\loop test.txt")
right after your Do Until statement should fix this.