I'm currently developing an Outlook Application, which seemed to work perfectly during testing.
This code seems to work when the MSGBox("ASDFG") is in place (rsts.Count returns 1), but as soon as it is removed, the statement returns 0. I have tried to surpass this by adding Debug.Print's to see if that made any difference, but I still find that the code will only run correctly when the MSGBox is in place.
I even added a Timer1 interval to re-run the script every second if it returns 0.
Function myThread()
Dim oApp As Outlook.Application = CreateObject("Outlook.application")
Dim sch As Outlook.Search
Dim rsts As Outlook.Results
Dim i As Integer
Dim myTaskSearch As String = ToolStripStatusLabel2.Text
Dim strF As String = "urn:schemas:mailheader:subject LIKE '%Task: " & myTaskSearch & "%'"
Const strS As String = "Inbox"
Try
sch = oApp.AdvancedSearch(strS, strF)
rsts = sch.Results
MsgBox("ASDFG")
Debug.Print(sch.Results.ToString)
Debug.Print("'" & myTaskSearch & "'")
If rsts.Count = 0 Then
Debug.Print(rsts.Count)
Timer1.Interval = 1000
Timer1.Start()
End If
For i = 1 To rsts.Count
Debug.Print(i)
Timer1.Stop()
TabControl1.TabPages.Add(i)
'rsts.Item(i).Body
'rsts.Item(i).SenderName
Next
Catch ex As System.Exception
MsgBox(ex.ToString)
End Try
End Function
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
myThread()
End Sub
With MSGBox
Without MSGBox + Debug
Add an event handler to be called when the search is complete. As GSerg said, AdvancedSearch is asynchronous so it is still running when your code prints the count.
See the documentation for a code example.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
The following code is a part of VB6 application & I'm currently converting to VB.NET Windows Service. Line starts with Open gives me an error(I assume the 'Open' syntax does not support with VB.NET). I tried converting the code utilizing all the VB.NET knowledge I have but would like to know the ideal/optimistic solution.
VB6 Code
Private Sub Text1_GotFocus()
Me.lblCompanyName.Caption = ""
Me.lblCompanyName.Refresh
lngPosted = 0
lngSkipped = 0
lngClosed = 0
strMsg = Dir(strPath & "\WisysDataCollector_*.log", vbNormal)
Do While strMsg <> ""
On Error Resume Next
If strMsg < "WisysDataCollector_" & Format(DateAdd("m", -12, Now), "yyyyMM") Then
Kill(strPath & "\" & strMsg)
End If
On Error GoTo 0
strMsg = Dir()
Loop
datTimeStart = Now
Do
On Error Resume Next
Open strPath & "\WisysDataCollector_" & Format(Now, "yyyyMM") & ".log" For Append Lock Read Write As #1
lngST = Err.Number
strMsg = Err.Description
On Error GoTo 0
If lngST = 0 Then
Exit Do
End If
dblTimeElapsed = (Now - datTimeStart) * 24 * 60 * 60
If dblTimeElapsed > 20 Then
varResponse = vbCancel
If varResponse = vbCancel Then
strStatus = "Log file busy. Process aborted."
GoTo EXITFORM
End If
datTimeStart = Now
End If
Loop
Code continues.......
What I've tried : Created a 'FileIO' class as following with IO.StreamWriter and IO.StreamReader
Public Class FileIO
Public Shared Sub WriteLog(strToWrite As String)
Dim filePath As String = AppDomain.CurrentDomain.BaseDirectory + "\WisysDataCollector_" + Format(Now, "MMddyy") + ".log"
Dim streamWr As IO.StreamWriter = Nothing
Try
streamWr = New IO.StreamWriter(filePath, True)
streamWr.Write(Now + " - " + strToWrite + vbNewLine)
streamWr.Flush()
streamWr.Close()
Catch ex As Exception
End Try
End Sub
Public Shared Sub ReadLog(strToWrite As String)
Dim filePath As String = AppDomain.CurrentDomain.BaseDirectory + "\WisysDataCollector_" + Format(Now, "MMddyy") + ".log"
Dim streamRd As IO.StreamReader = Nothing
Try
streamRd = New IO.StreamReader(filePath, True)
streamRd.Read()
streamRd.Close()
Catch ex As Exception
End Try
End Sub
End Class
Please let me know the errors I've made in the above code also how should I use the 'FileIO' class to correct the errors with 'Open' and 'Print #1'?
Also if someone can please clarify what were they trying to do by this code line(honestly I'm trying to understand but not sure why they've multiplied the time difference by 24 * 60 * 60) dblTimeElapsed = (Now - datTimeStart) * 24 * 60 * 60?
The ampersand, &, is the concatenation character for vb.net. Although the plus sign will usually work, if numbers are involved you could get unexpected results.
Streams must be disposed to released unmanaged resources. Using...End Using blocks take care of this for us.
I made filePath a class level variable because it is used in more than one method. This must also be Shared because it is used in Shared methods. I changed the format of date so it will appear chronologically in File Explorer.
It makes no sense to read the log and do nothing with it. I changed the ReadLog method to a Function. It also makes no sense to pass a string to it.
I believe the vb6 code was trying to express elapsed time in seconds with the 24 60 60 business. I gave you an example of that with the Form.Load setting the startTime and then hitting a button some time later and calculating the seconds that had passed.
In the form class...
Private StartTime As DateTime
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StartTime = Now
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FileIO.WriteLog(TextBox1.Text)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = FileIO.ReadLog
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim elapsedTime As TimeSpan = Now - StartTime
Dim TotalSeconds = elapsedTime.TotalSeconds
MessageBox.Show($"The elapsed time since the program started is {TotalSeconds}")
End Sub
Your class would look like this...
Public Class FileIO
Private Shared filePath As String = AppDomain.CurrentDomain.BaseDirectory & "\WisysDataCollector_" & Format(Now, "yyyyMMdd") & ".log"
Public Shared Sub WriteLog(strToWrite As String)
Using sw = File.AppendText(filePath)
sw.WriteLine(strToWrite)
End Using
End Sub
Public Shared Function ReadLog() As String
If File.Exists(filePath) Then
Return File.ReadAllText(filePath)
Else
Return ""
End If
End Function
End Class
Long time reader, first time poster. Usually I'm able to find the answer and make it work. Not this time..... I'm using VB.NET in VS2013. I am trying to update a progress bar with work done in a secondary thread. Easy right? No. I had to make it more complicated. The progress bar (ToolStripProgressBar1) is on the main form (frmMain), the MDI of the project. A secondary form (frmShipping) has a button which initiates a second thread to do some COMM Port communications in a class (cApex). I can get the progress bar to update on the frmMain from the main UI thread (frmShipping button).
This is the code from button on frmShiping and the multithread procedure:
Private Sub btnreadScanner_Click(sender As Object, e As EventArgs) Handles btnreadScanner.Click
Dim thrReadScanner As New System.Threading.Thread(AddressOf ReadScanner)
thrReadScanner.IsBackground = True
thrReadScanner.Start()
End Sub
Private Sub ReadScanner()
Dim strRowCount As String
ShipmentMsg(2)
strRowCount = objShipping.RecordsExisit.ToString()
Try
objApex.ImmediateMode()
If objApex.FileDownload = False Then
Throw New Exception(Err.Description)
End If
Catch ex As Exception
ShipmentMsg(1)
MessageBox.Show("No Data downloaded from Scanner. Try Again. Error#: " & Err.Number & " : " & Err.Description)
Exit Sub
End Try
RecordCount()
DataGridUpdate()
btnProcessShipment.Enabled = True
ShipmentMsg(5)
ScanErrors()
End Sub
This all works great. As expected. The call to objApex.FileDownload in class cApex is where progress bar is to be updated from (actually in another function called from FileDownload). So here is the code there.
Try
GetHeaderRecord()
If Count <> 0 Then intTicks = Math.Round((100 / Count), 1)
For intcount As Integer = 1 To Count
Dim intLength As Integer = Length
Do While intLength > 0
literal = Chr(_serialPort.ReadChar.ToString)
If literal = ">" Then Exit Do
strRecord = strRecord & literal
intLength = intLength - 1
Loop
REF = strRecord.Substring(0, 16).TrimEnd
SKID = strRecord.Substring(16, 16).TrimEnd
REEL_BC = strRecord.Substring(32, 15).TrimEnd
ScanDate = strRecord.Substring(47, 8).TrimEnd
ScanDate = DateTime.ParseExact(ScanDate, "yyyyMMdd", Nothing).ToString("MM/dd/yyyy")
ScanTime = strRecord.Substring(55, 6).TrimEnd
ScanTime = DateTime.ParseExact(ScanTime, "HHmmss", Nothing).ToString("HH:mm:ss")
strRecordTotal = strRecordTotal & strRecord & CRLF
Dim strSQL As String
strSQL = "INSERT INTO tblScanData (PONo,Barcode,SkidNo,ScanDate,ScanTime) " & _
"VALUES (" & _
Chr(39) & REF & Chr(39) & _
"," & Chr(39) & REEL_BC & Chr(39) & _
"," & Chr(39) & SKID & Chr(39) & _
"," & Chr(39) & ScanDate & Chr(39) & _
"," & Chr(39) & ScanTime & Chr(39) & ")"
objData.Executecommand(strSQL)
strRecord = ""
Next
And finally this is how I was calling the progress bar update.
Dim f As frmMain = frmMain
System.Threading.Thread.Sleep(100)
DirectCast(f, frmMain).ToolStripProgressBar1.PerformStep()
I really need to put the PerformStep in the For loop. Each time around the loop will step the progress bar the percentage of steps needed to make bar fairly accurate (done by the math code before loop). Also I setup the properties of the progress bar control on frmMain. So, am I crazy, or is there a way to accomplish this? I tried using a delegate; Me.Invoke(New MethodInvoker(AddressOf pbStep)) to make code cross thread safe. I don't get an error about cross thread calls, but the progress bar doesn't update either. Sorry it's a long one but I'm lost and my ADHD won't let me scrap this idea.
EDIT AS REQUESTED:
Public Sub pbStep()
Dim f As frmMain = frmMain
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf pbStep))
Else
DirectCast(f, frmMain).ToolStripProgressBar1.PerformStep()
System.Threading.Thread.Sleep(100)
End If
End Sub
Both responses helped lead me to the correct answer I was needing. The code provided by James was a great starting point to build on, and Hans has several post explaining the BackgroundWorker. I wanted to share the "Answer" I came up with. I'm not saying its the best way to do this, and I'm sure I'm violating some rules of common logic. Also, a lot of the code came from a MSDN example and James's code.
Lets start with the form from which I am calling the bgw, frmShipping. I added this code:
Dim WithEvents bgw1 As New System.ComponentModel.BackgroundWorker
Private Sub bgw1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles bgw1.RunWorkerCompleted
If e.Error IsNot Nothing Then
MessageBox.Show("Error: " & e.Error.Message)
ElseIf e.Cancelled Then
MessageBox.Show("Process Canceled.")
Else
MessageBox.Show("Finished Process.")
End If
End Sub
Private Sub bgw1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
Handles bgw1.ProgressChanged
DirectCast(Me.MdiParent, frmMain).ToolStripProgressBar1.Maximum = 1960
DirectCast(Me.MdiParent, frmMain).ToolStripProgressBar1.Step = 2
Dim state As cApex.CurrentState =
CType(e.UserState, cApex.CurrentState)
DirectCast(Me.MdiParent, frmMain).txtCount.Text = state.LinesCounted.ToString
DirectCast(Me.MdiParent, frmMain).txtPercent.Text = e.ProgressPercentage.ToString
DirectCast(Me.MdiParent, frmMain).ToolStripProgressBar1.PerformStep()
End Sub
Private Sub bgw1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) _
Handles bgw1.DoWork
Dim worker As System.ComponentModel.BackgroundWorker
worker = CType(sender, System.ComponentModel.BackgroundWorker)
Dim objApex As cApex = CType(e.Argument, cApex)
objApex.CountLines(worker, e)
End Sub
Sub StartThread()
Me.txtCount.Text = "0"
Dim objApex As New cApex
bgw1.WorkerReportsProgress = True
bgw1.RunWorkerAsync(objApex)
End Sub
Next I added the following code the my cApex class.
Public Class CurrentState
Public LinesCounted
End Class
Private LinesCounted As Integer = 0
Public Sub CountLines(ByVal worker As System.ComponentModel.BackgroundWorker, _
ByVal e As System.ComponentModel.DoWorkEventArgs)
Dim state As New CurrentState
Dim line = ""
Dim elaspedTime = 20
Dim lastReportDateTime = Now
Dim lineCount = File.ReadAllLines(My.Settings.strGenFilePath).Length
Dim percent = Math.Round(100 / lineCount, 2)
Dim totaldone As Double = 2
Using myStream As New StreamReader(My.Settings.strGenFilePath)
Do While Not myStream.EndOfStream
If worker.CancellationPending Then
e.Cancel = True
Exit Do
Else
line = myStream.ReadLine
LinesCounted += 1
totaldone += percent
If Now > lastReportDateTime.AddMilliseconds(elaspedTime) Then
state.LinesCounted = LinesCounted
worker.ReportProgress(totaldone, state)
lastReportDateTime = Now
End If
System.Threading.Thread.Sleep(2)
End If
Loop
state.LinesCounted = LinesCounted
worker.ReportProgress(totaldone, state)
End Using
End Sub
I also added a couple of text boxes to my main form to show the current line count from the file being read from and the overall progress as a percentage of a 100. Then on the Click event of my button I just call StartThread(). It is not 100% accurate, but its close enough to give the user a very good idea where the process stands. I have a little more work to do to add it to the "ReadScanner" function, where I originally was wanting to use the progress bar. But this function it the longer of the two that I perform on the scanner, writing almost 2,000 lines of code through a COMM Port. I'm happy with the results.
Thank you guys for helping out!
P.S. I have also now added variables to set the pbar.Maximum and the pbar.step since those can change if the scanner file is changed.
Background workers are useful for this purpose. Just use it in combination with a delegate. All the threaded work is done within the DoWork event of the worker. As progress is made, progress is reported within the DoWork event. This in turn fires the ProgressedChanged event of the worker class which is on the same thread as the progressbar. Once the DoWork has completed and is out of scope, the RunWorkerCompleted event is fired. This can be used to do inform the user that the task is complete, etc. Here is a working solution that I threw together. Just paste it behind an empty form and run.
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Threading
Public Class Form1
Private _progressBar As ProgressBar
Private _worker As BackgroundWorker
Sub New()
' This call is required by the designer.
InitializeComponent()
Initialize()
BindComponent()
End Sub
Private Sub Initialize()
_progressBar = New ProgressBar()
_progressBar.Dock = DockStyle.Fill
_worker = New BackgroundWorker()
_worker.WorkerReportsProgress = True
_worker.WorkerSupportsCancellation = True
Me.Controls.Add(_progressBar)
End Sub
Private Sub BindComponent()
AddHandler _worker.ProgressChanged, AddressOf _worker_ProgressChanged
AddHandler _worker.RunWorkerCompleted, AddressOf _worker_RunWorkerCompleted
AddHandler _worker.DoWork, AddressOf _worker_DoWork
AddHandler Me.Load, AddressOf Form1_Load
End Sub
Private Sub Form1_Load()
_worker.RunWorkerAsync()
End Sub
Private Sub _worker_ProgressChanged(ByVal o As Object, ByVal e As ProgressChangedEventArgs)
_progressBar.Increment(e.ProgressPercentage)
End Sub
Private Sub _worker_RunWorkerCompleted(ByVal o As Object, ByVal e As RunWorkerCompletedEventArgs)
End Sub
Private Sub _worker_DoWork(ByVal o As Object, ByVal e As DoWorkEventArgs)
Dim worker = DirectCast(o, BackgroundWorker)
Dim value = 10000
SetProgressMaximum(value)
For x As Integer = 0 To value
Thread.Sleep(100)
worker.ReportProgress(x)
Next
End Sub
Private Sub SetProgressMaximum(ByVal max As Integer)
If _progressBar.InvokeRequired Then
_progressBar.Invoke(Sub() SetProgressMaximum(max))
Else
_progressBar.Maximum = max
End If
End Sub
End Class
I am working on windows form application :
in my form am filling my datagrid view in some interval.so some time my application getting stuck..so i used back ground worker and timer
in back ground worker i am calling my function to fill the my data grid view.i set Timer Interval as 10000. in background worker i given code like this:
Private Sub BackgroundWorker1_DoWork
Call Fetch_Info()
End Sub
in Timer click event i given code like thise:
If Not BackgroundWorker1.IsBusy Then
BackgroundWorker1.RunWorkerAsync()
End If
my Fetch_Info() function like this:
Dim cnt As Integer
Dim tbarcodedgv As String
Dim totaltbarcode As String
cnt = DGVall.RowCount
Dim tbar As String
Dim locTable As New DataTable
locTable.Columns.Add("carid", GetType(String))
If cnt > 0 Then
For i = 0 To cnt - 2
tbarcodedgv = DGVall.Rows(i).Cells(0).Value
locTable.Rows.Add(tbarcodedgv)
Next
End If
Dim flag As Boolean = False
Dim dcnt As Integer = DGVall.RowCount
Dim trid As Integer
Dim tbarcode As String
Dim keyloc As String
Dim cmd23 As New SqlCommand("IBS_fetchrequested", con.connect)
cmd23.CommandType = CommandType.StoredProcedure
cmd23.Parameters.Add("#tid", SqlDbType.Int).Value = tid
If cnt > 1 Then
Dim tvp1 As SqlParameter = cmd23.Parameters.AddWithValue("#Tbaroced", locTable)
tvp1.SqlDbType = SqlDbType.Structured
tvp1.TypeName = "dbo.TBarcode"
End If
dr = cmd23.ExecuteReader
While dr.Read
flag = False
tbarcode = dr("TBarcode")
If flag = False Then
If dr("keyloc") Is DBNull.Value Then
keyloc = ""
Else
keyloc = dr("keyloc")
End If
Dim row0 As String() = {tbarcode, keyloc, "", "Release"}
DGVall.Rows.Add(row0)
AxWindowsMediaPlayer1.URL = "C:\Beep.mp3"
End If
End While
dr.Close()
con.disconnect()
While your background worker runs in another thread than your GUI you are manipulating the Datagridview that's running in the GUI's thread. This should usually not work at all but it is probably the reason, why your GUI hangs while the BGW is running.
Try splitting the work: The time consuming fetching of data from the database is carried out in the Backgroundworker's DoWork event handler and you set the results as the e.Result value of the EventArgs variable in the DoWork function.
Then you handle the Backgroundworker's RunWorkerCompleted event and there you quickly update your datagridview with the results you set in the DoWork method. That way your GUI has nothing to do with the actual time consuming task and will only be affected by the quick update of your datagridview.
The code example for this is:
Public Class Form1
Private WithEvents LazyBGW As New System.ComponentModel.BackgroundWorker
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This code runs in the UI-Thread
LazyBGW.RunWorkerAsync()
End Sub
Private Sub LazyBGW_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles LazyBGW.DoWork
'This code runs in the BGW-Thread
Dim a As Integer = 0
For i = 1 To 5
a += 1
'I'm a lazy worker, so after this hard work I need to...
Threading.Thread.Sleep(1000) 'This locks up the BGW-Thread, not the UI-thread
Next
'Work is done, put results in the eventargs-variable for further processing
e.Result = a
End Sub
Private Sub LazyBGW_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles LazyBGW.RunWorkerCompleted
'This code runs in the UI-Thread
Dim results As Integer = CInt(e.Result) 'e.Result contains whatever you put into it in the DoWork() method
MessageBox.Show("Finally the worker is done and our result is: " & results.ToString)
End Sub
End Class
The following code will extract files modified today from the SourceDirectory and place them into the FilesExtracted folder, then the batch file will delete the rest of the files in the sourceDirectory. But after that is all done a brand new set of files will be copied from the OriginalTestFiles folder and put into the sourceDirectory, but its does not do it. Does anyone think that it could be because the batch files hasn't stopped its operations and is still deleting the files in the sourceDirectory, or is there another problem. Thank You all!
Imports System.IO
Public Class frmExtractionator
' Dim txtFiles1 As Control
Dim sourceDirectory As String = "F:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "F:\FilesExtracted"
Dim originalDirectory As String = "F:\OriginalTestFiles"
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
If (IO.File.GetLastWriteTime(currentFileLoc).ToString("MM/dd/yyyy") = DateTime.Now.ToString("MM/dd/yyyy")) Then
MessageBox.Show(currentFileLoc & " moved", "Moved Succesfully")
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
System.Diagnostics.Process.Start("F:\poop.bat")
Try
Dim txtFiles2 = Directory.EnumerateFiles(originalDirectory)
For Each currentFileLoc2 As String In txtFiles2
Dim fileName = currentFileLoc2.Substring(originalDirectory.Length + 1)
File.Move(currentFileLoc2, Path.Combine(sourceDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class
You can get the process as a variable once you start it and wait for it to exit:
Dim theProcess As Process = Process.Start("F:\poop.bat")
theProcess.WaitForExit()
Try monitoring the Process for completion...
'Start the process.
Dim Proc = Process.Start("F:\poop.bat")
'Wait for the window to finish loading.
Proc.WaitForInputIdle()
'Wait for the process to end.
Proc.WaitForExit()
...
Today I decided to come up with a program that would be useful for me in VB.net (I have never coded in VB.net before). All is going fine up till this point but I have hit a snag with the error mentioned above. The problem is with the windowssevenexistsonsource boolean under the get get of profiles comment. I will also take any code criticism well as I would like to get out of bad practices before I start! (the sub does end but I have not included that code)
Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Check that the entries required are not empty
If String.IsNullOrEmpty(sourceipaddress.Text) Or String.IsNullOrEmpty(destinationipaddress.Text) Then
MsgBox("Source or destination IP address is empty")
Exit Sub
End If
'First we need to establish the operating system of the source and destination
Try
Dim windowssevenexistsonsource As Boolean = IO.Directory.Exists("\\" & sourceipaddress.Text & "\c$\users")
Dim windowssevenexistsondestination As Boolean = IO.Directory.Exists("\\" & sourceipaddress.Text & "\c$\users")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
'Now we need to get a list of profiles in the relevant directory and put them into an array
'Declare variables and empty the array
Dim Sourcedirectorylistarray, destinationdirectorylistarray As String()
Dim sourcedirectoryentry, destinationdirectoryentry As String
Dim Sourcerootpath, destinationrootpath As String
'Get List of Profiles
Try
If windowssevenexistsonsource = True Then
Sourcedirectorylistarray = System.IO.Directory.GetDirectories("\\" & sourceipaddress.Text & "\c$\users\")
destinationdirectorylistarray = System.IO.Directory.GetDirectories("\\" & destinationipaddress.Text & "\c$\users\")
Else
MsgBox("test")
End If
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
In declaring your variables windowssevenexitsonsource and windowssevenexistsondestination in your try block you are limiting their scope to the try block. Try declaring them at the beginning of your subroutine.