I'm new in programming. this is the first system application that I did. I'm struggling in closing or killing the excel application once the system has successfully uploaded in a repository. this is my code. I do hope you can help me to fix it. thank you in advance.
Private Sub bgw_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgw.DoWork
srcXlApp = New Excel.Application
dstXlApp = New Excel.Application
Dim numToDo As Integer = CInt(e.Argument)
Dim ComputerName As String
Dim strMissingValues As String
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(srcXlWb)
System.Runtime.InteropServices.Marshal.ReleaseComObject(dstXlWb)
isValidUploading = True
strMissingValues = "Cannot upload there are missing fields: "
bgwState = e
strRemarks = txtRemarks.Text
srcXlApp.DisplayAlerts = False
srcXlWbs = srcXlApp.Workbooks
srcXlWb = srcXlWbs.Open(srcFilePath)
srcXlWrksht = srcXlWb.Worksheets(1)
srcXlApp.Visible = False
'Step 1 - open source
bgw.ReportProgress(Convert.ToInt32((1 / numToDo) * 100))
'System.Threading.Thread.Sleep(5000)
ComputerName = System.Net.Dns.GetHostName
'dstFilePath = "C:\Users\" & ComputerName & "\Desktop\Mazza\trunk\QA Task Monitoring_2020.xlsx"
If ComputerName = "jonas" Then
'MessageBox.Show(ComputerName)
dstFilePath = "C:\Users\jonas.ONE-SOURCE\Desktop\Mazza\trunk\QA Task Monitoring_for_testing_only.xlsx"
Else
dstFilePath = "C:\Users\" & ComputerName & "\Desktop\Mazza\trunk\QA Task Monitoring_for_testing_only.xlsx"
End If
'dstFilePath = "C:\Users\jonas.ONE-SOURCE\Desktop\Mazza\trunk\QA Task Monitoring_2020.xlsx"
'dstFilePath = "C:\Users\" & ComputerName & "\Desktop\Mazza\trunk\QA Task Monitoring_for_testing_only.xlsx"
dstXlApp.DisplayAlerts = False
dstXlWbs = dstXlApp.Workbooks
dstXlWb = dstXlWbs.Open(dstFilePath)
dstXlApp.Visible = False
'Step 2 - open destination
bgw.ReportProgress(Convert.ToInt32((2 / numToDo) * 100))
'System.Threading.Thread.Sleep(5000)
'Step 3 - Copy Range
bgw.ReportProgress(Convert.ToInt32((3 / numToDo) * 100))
'System.Threading.Thread.Sleep(3000)
'Code for copying cells
srcXlWrksht = srcXlWb.Worksheets(1)
strTicketNumber = srcXlWrksht.Range("B3").Value
strCID = srcXlWrksht.Range("B4").Value
strIteration = srcXlWrksht.Range("B13").Value
If Not IsNothing(strIteration) Then
strIteration = strIteration.Substring(2)
End If
strSystem = srcXlWrksht.Range("B17").Value
strAssignedBy = srcXlWrksht.Range("B10").Value
strPMOBA = srcXlWrksht.Range("B9").Value
strRequest = srcXlWrksht.Range("B5").Value
strAssign = srcXlWrksht.Range("B6").Value
strStart = srcXlWrksht.Range("B14").Value
strEnd = srcXlWrksht.Range("B15").Value
strStatus = srcXlWrksht.Range("C24").Value
strTask = srcXlWrksht.Range("B16").Value
If srcXlWb.Worksheets.Count >= 2 Then
srcXlWrksht = srcXlWb.Worksheets(2)
strDescription = srcXlWrksht.Range("D3").Value
Else
'strMissingValues = strMissingValues & vbCrLf & "Title/Description"
isValidUploading = False
End If
'srcXlWrksht = srcXlWb.Worksheets(2)
'strDescription = srcXlWrksht.Range("D3").Value
If strTicketNumber = "" Then
strMissingValues = strMissingValues & vbCrLf & "Ticket ID"
isValidUploading = False
End If
If strCID = "" Then
strMissingValues = strMissingValues & vbCrLf & "Change ID"
isValidUploading = False
End If
If strIteration = "" Then
strMissingValues = strMissingValues & vbCrLf & "Iteration Number"
isValidUploading = False
End If
If strSystem = "" Then
strMissingValues = strMissingValues & vbCrLf & "System Name"
isValidUploading = False
End If
If strAssignedBy = "" Then
strMissingValues = strMissingValues & vbCrLf & "Assigned By"
isValidUploading = False
End If
If strPMOBA = "" Then
strMissingValues = strMissingValues & vbCrLf & "Assigned PMO/BA"
isValidUploading = False
End If
If strRequest = "" Then
strMissingValues = strMissingValues & vbCrLf & "Requested Date"
isValidUploading = False
End If
If strAssign = "" Then
strMissingValues = strMissingValues & vbCrLf & "Assigned Date"
isValidUploading = False
End If
If strStart = "" Then
strMissingValues = strMissingValues & vbCrLf & "Start Date"
isValidUploading = False
End If
If strEnd = "" Then
strMissingValues = strMissingValues & vbCrLf & "End Date"
isValidUploading = False
End If
If strStatus = "" Then
strMissingValues = strMissingValues & vbCrLf & "Status"
isValidUploading = False
End If
If strTask = "" Then
strMissingValues = strMissingValues & vbCrLf & "Task type"
isValidUploading = False
End If
If strDescription = "" Then
strMissingValues = strMissingValues & vbCrLf & "Title/Description"
isValidUploading = False
End If
'If CheckBox1.CheckState = CheckState.Checked And txtRemarks.Text = "" Then
' strMissingValues = strMissingValues & vbCrLf & "Empty Remarks"
' MessageBox.Show("Please input remarks", "Empty Remarks", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
' isValidUploading = False
'End If
If Not isValidUploading Then
MessageBox.Show(strMissingValues, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
srcXlWb.Close()
dstXlWb.Close()
srcXlApp.UserControl = True
dstXlApp.UserControl = True
srcXlApp.Quit()
dstXlApp.Quit()
Marshal.ReleaseComObject(dstXlWrksht)
Marshal.ReleaseComObject(dstXlWb)
Marshal.ReleaseComObject(dstXlWbs)
Marshal.ReleaseComObject(dstXlApp)
Marshal.ReleaseComObject(dstXlWrksht)
Marshal.ReleaseComObject(srcXlWb)
Marshal.ReleaseComObject(srcXlWbs)
Marshal.ReleaseComObject(srcXlApp)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
bgw.CancelAsync()
e.Cancel = True
Exit Sub
End If
'strTicketNumber = srcXlWrksht.Range("B4").Value.ToString
'code for pastespecial
dstXlWb.Worksheets("Tasks").Range("A3").Select()
Last_Row = dstXlWb.Worksheets("Tasks").Range("A3").End(Excel.XlDirection.xlDown).Row + 1
dstXlWb.Worksheets("Tasks").Range("A" & Last_Row).Select()
'Step 4 - Pasting values
bgw.ReportProgress(Convert.ToInt32((4 / numToDo) * 100))
'System.Threading.Thread.Sleep(3000)
dstXlWb.Worksheets("Tasks").Range("C" & Last_Row).Value = strTicketNumber
dstXlWb.Worksheets("Tasks").Range("B" & Last_Row).Value = strQAT
dstXlWb.Worksheets("Tasks").Range("D" & Last_Row).Value = strCID
dstXlWb.Worksheets("Tasks").Range("E" & Last_Row).Value = strIteration
dstXlWb.Worksheets("Tasks").Range("F" & Last_Row).Value = strDescription
dstXlWb.Worksheets("Tasks").Range("G" & Last_Row).Value = strSystem
dstXlWb.Worksheets("Tasks").Range("H" & Last_Row).Value = strAssignedBy
dstXlWb.Worksheets("Tasks").Range("I" & Last_Row).Value = strPMOBA
dstXlWb.Worksheets("Tasks").Range("J" & Last_Row).Value = strSBU
dstXlWb.Worksheets("Tasks").Range("K" & Last_Row).Value = strTypes
dstXlWb.Worksheets("Tasks").Range("L" & Last_Row).Value = strProcess
dstXlWb.Worksheets("Tasks").Range("M" & Last_Row).Value = strRequest
dstXlWb.Worksheets("Tasks").Range("N" & Last_Row).Value = strAssign
dstXlWb.Worksheets("Tasks").Range("O" & Last_Row).Value = strStart
dstXlWb.Worksheets("Tasks").Range("P" & Last_Row).Value = strEnd
dstXlWb.Worksheets("Tasks").Range("Q" & Last_Row).Value = strStatus
dstXlWb.Worksheets("Tasks").Range("S" & Last_Row).Value = strRemarks
dstXlWb.Worksheets("Tasks").Range("Y" & Last_Row).Value = strTask
dstXlWb.Worksheets("Tasks").Range("W" & Last_Row).Value = "=+TEXT(QATM[[#This Row],[End Date]]," & """MM""" & ")"
dstXlWb.Worksheets("Tasks").Range("X" & Last_Row).Value = "=+TEXT(QATM[[#This Row],[End Date]]," & """YYYY""" & ")"
If CheckBox1.CheckState = CheckState.Checked Then
dstXlWb.Worksheets("Tasks").Range("R" & Last_Row).Value = "=""FOR QAT"" " & "& " & "TEXT(" & dstXlWb.Worksheets("Tasks").Range("E" & Last_Row).Value + 1 & ", ""00"")"
Else
dstXlWb.Worksheets("Tasks").Range("R" & Last_Row).Value = "YES"
End If
'Step 5 - Saving
bgw.ReportProgress(Convert.ToInt32((5 / numToDo) * 100))
'System.Threading.Thread.Sleep(3000)
dstXlApp.ActiveWorkbook.Save()
Catch ex As Exception
'MsgBox(ex.Message)
Me.Cursor = Cursors.Default
MessageBox.Show("Please check excel file.")
'MsgBox("Error has occured. " & ex.Message, MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Error")
bgw.CancelAsync()
Exit Sub
srcXlWb.Close()
dstXlWb.Close()
srcXlApp.UserControl = True
dstXlApp.UserControl = True
srcXlApp.Quit()
dstXlApp.Quit()
Marshal.ReleaseComObject(dstXlWb)
Marshal.ReleaseComObject(dstXlWbs)
Marshal.ReleaseComObject(dstXlApp)
Marshal.ReleaseComObject(srcXlWb)
Marshal.ReleaseComObject(srcXlWbs)
Marshal.ReleaseComObject(srcXlApp)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
Finally
'srcXlWb.Close()
'dstXlWb.Close()
'srcXlApp.UserControl = True
'dstXlApp.UserControl = True
'srcXlApp.Quit()
'dstXlApp.Quit()
Marshal.ReleaseComObject(dstXlWb)
Marshal.ReleaseComObject(dstXlWbs)
Marshal.ReleaseComObject(dstXlApp)
Marshal.ReleaseComObject(srcXlWb)
Marshal.ReleaseComObject(srcXlWbs)
Marshal.ReleaseComObject(srcXlApp)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
End Sub
Private Declare Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hwnd As IntPtr,
ByRef lpdwProcessId As Integer) As Integer
Friend Sub KillSpecificExcel(xlsApplication As Excel.Application)
Try
Dim psi As ProcessStartInfo = New ProcessStartInfo
Dim XLProcID As Integer = 0
Dim hwd As Integer
hwd = xlsApplication.Hwnd
GetWindowThreadProcessId(hwd, XLProcID)
Dim XLProc As Process = Process.GetProcessById(XLProcID)
psi.Arguments = $"/PID {XLProc.Id} /T /F"
psi.FileName = "taskkill"
Dim p As Process = New Process()
p.StartInfo = psi
p.Start()
Catch ex As Exception
Throw
End Try
End Sub
Related
I'm looping through a folder and grabbing data points. The code below works, but I don't know how to get it to add the new data for each workbook below. It currently just pastes over each other. I tried to use i as an integer and count the number of folders and command to add 5 rows for each folder but my loop cancels out the next loop somehow. not to mention i don't know how to make it add for the next workbook. So I just need it to open the workbook, grab this data, close the workbook, open the next one, grab the same information and just put that right below what the previous workbook did.
My formatting simply needs to grab the copy range and copy the exact same range down to the last row.
Sub loopwb()
'Dim fc As Integer
'Dim sc As Range
fn = dir("C:\Users\user\Desktop\folder\*xlsx")
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set wb = ThisWorkbook
Set ws = wb.Worksheets("List")
'Set sc = ws.Range("B11")
Do Until Len(fn) = 0
'Debug.Print fn
Set nwb = Workbooks.Open("C:\Users\user\Desktop\folder\" & fn)
Set nws = nwb.Worksheets("sht1")
ws.Range("B10").Value2 = "text"
ws.Range("B11").Value2 = nws.Range("A4").Value2
'change b11 to sc to initiate variable sequence
ws.Range("C11").Value2 = nws.Range("J6").Value2
ws.Range("H11").Value2 = nws.Range("P17").Value2
ws.Range("I11").Value2 = nws.Range("S17").Value2
ws.Range("K11").Value2 = nws.Range("S18").Value2
ws.Range("L11").Value2 = ", WAL"
ws.Range("M11").Value2 = nws.Range("L13").Value2
ws.Range("B12").Value2 = Chr(149) & " " & "text"
ws.Range("J11").Value2 = "text " & (nws.Range("E13").Value2 * 100) & " text:"
ws.Range("C12").Value2 = nws.Range("C16").Value2
ws.Range("H14").Value2 = Chr(149) & " " & "text:"
ws.Range("I14").Value2 = nws.Range("H36").Value2
ws.Range("B13").Value2 = Chr(149) & " " & "text:"
ws.Range("C13").Value2 = nws.Range("C20").Value2
ws.Range("B14").Value2 = Chr(149) & " " & "text:"
ws.Range("C14").Value2 = nws.Range("C14").Value2
ws.Range("H13").Value2 = Chr(149) & " " & "text:"
ws.Range("I13").Value2 = nws.Range("C17").Value2
If nws.Range("S10") = "text" Then
ws.Range("B15").Value2 = Chr(149) & " " & "text"
Else
ws.Range("B15").Value2 = Chr(149) & " " & "text"
End If
ws.Range("B16").Value2 = Chr(149) & " " & "text: " & nws.Range("S9").Value2
ws.Range("H16").Value2 = Chr(149) & " " & "text:"
ws.Range("I16").Value2 = nws.Range("S19").Value2
ws.Range("H15").Value2 = Chr(149) & " " & "text:"
ws.Range("I15").Value2 = nws.Range("H34").Value2
ws.Range("H12").Value2 = Chr(149) & " " & "text " & nws.Range("S11").Value2
nwb.Close savechanges:=False
fn = dir
Loop
Call format
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Sub format()
Dim cr As Range
Dim hr As Range
Dim lr As Long
Dim i As Integer
Set ws = ThisWorkbook.Worksheets("List")
With ws
Columns("B:M").EntireColumn.AutoFit
.Range("B11:M11").Font.Bold = True
.Range("B11:M11").Interior.Color = RGB(0, 48, 87)
.Range("B11:M11").Font.Color = RGB(255, 255, 255)
.Range("B16").Font.Bold = True
.Range("B15").Font.Bold = True
.Range("C12").NumberFormat = "#.000%"
.Range("C12").HorizontalAlignment = xlLeft
.Range("C16").Font.Bold = True
.Range("C16").HorizontalAlignment = xlLeft
.Range("K11").NumberFormat = "#.000%"
.Range("M11").NumberFormat = "General"
.Range("I14").NumberFormat = "#"
.Range("I14").HorizontalAlignment = xlLeft
.Range("I16").NumberFormat = "#.000%"
.Range("I15").NumberFormat = "$#,#"
.Range("I15").HorizontalAlignment = xlLeft
.Range("I13").HorizontalAlignment = xlLeft
.Range("I13").NumberFormat = "#0.000%"
Columns("D:E").ColumnWidth = 4
.Range("B10:M10").Font.Bold = True
.Range("B10:M10").Interior.Color = RGB(91, 160, 220)
.Range("B10:M10").Font.Color = RGB(255, 255, 255)
Set cr = .Range("B11:M16")
Set hr = .Range("B10:M10")
lr = .Range("B" & .Rows.count).End(xlUp).Row
'cr.Copy
' For i = 11 To lr Step 6
' PasteSpecial Paste:=xlPasteFormats
' Next i
End With
End Sub
I'm trying to send emails to each student contain the (student name and his marks ) using VBA ..
I have excel sheet as below
From above excel i need to send email to each student with email body text as below
Hi " Student name "
Below you can found your marks:-
Math :- " his mark"
Network :- "his mark"
Physics :- "his mark"
Antenna :- " his mark"
I already wort the code in VBA , but i don't know how send like this text to each student in the mailBody section ..
My code as below
Sub SendMail()
Dim objEmail
Const cdoSendUsingPort = 2 ' Send the message using SMTP
Const cdoBasicAuth = 1 ' Clear-text authentication
Const cdoTimeout = 100 ' Timeout for SMTP in seconds
mailServer = "smtp.gmail.com"
SMTPport = 465 '25 'SMTPport = 465
mailusername = Range("j9").Value
mailpassword = Range("j10").Value
''''''''
Dim n As Integer
n = Application.WorksheetFunction.CountA(Range("c:c")) - 1
For i = 1 To n
mailto = Range("c1").Offset(i, 0).Value
mailSubject = Range("e1").Offset(i, 0).Value
**mailBody = ??** What i should to set ?
Set objEmail = CreateObject("CDO.Message")
Set objConf = objEmail.Configuration
Set objFlds = objConf.Fields
With objFlds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = mailServer
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SMTPport
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = cdoTimeout
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasicAuth
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = mailusername
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = mailpassword
.Update
End With
objEmail.To = mailto
objEmail.From = mailusername
objEmail.subject = mailSubject
objEmail.TextBody = mailBody
'objEmail.AddAttachment "C:\report.pdf"
objEmail.CC = Range("d1").Offset(i, 0).Value
objEmail.BCC = Range("k1").Offset(i, 0).Value
objEmail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objEmail = Nothing
Next i
End Sub
Kind Regards..
Try this approach, please:
mailBody = "Hy " & Range("B" & i) & "," & vbCrLf & vbCrLf & _
"Below you can find your marks:" & vbCrLf & vbCrLf & _
"Network: - " & Range("G" & i) & vbCrLf & _
"Physics: - " & Range("H" & i) & vbCrLf & _
"Antenna: - " & Range("I" & i)
And start the iteration from 2:
For i = 2 To n
Then no need to any Offset:
objEmail.CC = Range("d" & i).Value
objEmail.BCC = Range("k" & i).Value
I have code below for a print function created in VBA. When I select "Return from leave" under the drop down "Type of Change", my print macro prints as a "salary" change type, not "return from leave". I cant see where I went wrong in my code or what is causing the issue... Any thoughts? Thanks in advance!
Sub pcf_print()
Dim ws As Worksheet
Dim datasheet As Worksheet
Dim fs As Object
Dim str As String
Dim bool As Boolean
If Len(ActiveSheet.Name) < 3 Then
MsgBox "This worksheet is not a PCF"
Exit Sub
End If
If Left(ActiveSheet.Name, 3) <> "PCF" Then
MsgBox "This worksheet is not a PCF"
Exit Sub
End If
'MsgBox Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v")) 'Right(ActiveSheet.Name, 4)
If InStr(ActiveSheet.Name, " vv") Then
If (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " vv") - 1)) >= 1.2 And (ActiveSheet.Range("F10") = "(select)" Or ActiveSheet.Range("F10") = "" Or ActiveSheet.Range("F10") = "(sélect.)")) Then
MsgBox "This form has not been completed"
Exit Sub
End If
Else
If (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) < 1.2 And (ActiveSheet.Range("F9") = "(select)" Or ActiveSheet.Range("F9") = "")) Or (CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) >= 1.2 And (ActiveSheet.Range("F10") = "(select)" Or ActiveSheet.Range("F10") = "" Or ActiveSheet.Range("F10") = "(sélect.)")) Then
MsgBox "This form has not been completed"
Exit Sub
End If
End If
Set datasheet = ActiveSheet
If ActiveWorkbook.Worksheets("Form Lists").Range("CorpOrStore") = "Corp" Then
str = "Corporate"
Else
str = "Stores"
End If
Set fs = CreateObject("Scripting.FileSystemObject")
bool = fs.FolderExists("H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\")
If Not bool Then
MkDir "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\"
End If
If InStr(ActiveSheet.Name, " vv") Then
If CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " vv") - 1)) >= 1.2 Then
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & Replace(datasheet.Range("F10"), "/", "_") & " for " & datasheet.Range("J17") & ", " & datasheet.Range("F17") & " effective " & Month(datasheet.Range("F12")) & "-" & Day(datasheet.Range("F12")) & "-" & Year(datasheet.Range("F12")) & ".xls"
End If
Else
If CDbl(Right(ActiveSheet.Name, Len(ActiveSheet.Name) - 1 - InStr(ActiveSheet.Name, " v"))) >= 1.2 Then
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & Replace(datasheet.Range("F10"), "/", "_") & " for " & datasheet.Range("J17") & ", " & datasheet.Range("F17") & " effective " & Month(datasheet.Range("F12")) & "-" & Day(datasheet.Range("F12")) & "-" & Year(datasheet.Range("F12")) & ".xls"
Else
ActiveWorkbook.SaveAs "H:\HR\Online PCF Archive\" & str & "\" & Trim(datasheet.Range("StoreDeptResult")) & "\" & datasheet.Range("F9") & " for " & datasheet.Range("J16") & ", " & datasheet.Range("F16") & " effective " & Month(datasheet.Range("F11")) & "-" & Day(datasheet.Range("F11")) & "-" & Year(datasheet.Range("F11")) & ".xls"
End If
End If
Set ws = ActiveWorkbook.Worksheets("Payroll Forms")
If Right(ActiveSheet.Name, 5) = "v1.20" Then
ActiveWorkbook.Worksheets("Form Lists").Unprotect "0nl1n3"
ActiveWorkbook.Worksheets("Form Lists").Range("B8") = "A1:G76"
ActiveWorkbook.Worksheets("Form Lists").Range("B9") = "A80:G157"
ActiveWorkbook.Worksheets("Form Lists").Range("B10") = "A160:G225"
ActiveWorkbook.Worksheets("Form Lists").Range("B11") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B12") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B13") = "A228:G259"
ActiveWorkbook.Worksheets("Form Lists").Range("B14") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B15") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B16") = "A343:G367"
ActiveWorkbook.Worksheets("Form Lists").Range("B17") = "A263:G338"
ActiveWorkbook.Worksheets("Form Lists").Range("B18") = "A160:G225"
ActiveWorkbook.Worksheets("Form Lists").Range("B19") = "A370:G420"
ActiveWorkbook.Worksheets("Form Lists").Protect "0nl1n3"
End If
If Right(ActiveSheet.Name, 5) = "v1.20" Or Right(ActiveSheet.Name, 5) = "v1.21" Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
ActiveWorkbook.Unprotect "0nl1n3"
ws.Visible = xlSheetVisible
ws.PrintOut
ws.Visible = xlSheetHidden
ActiveWorkbook.Protect "0nl1n3"
ActiveWorkbook.Close False
End Sub
OP says:
When I select "Return from leave" under the drop down "Type of Change", my print macro prints as a "salary" change type, not "return from leave"
Assuming that the
"salary" change type
corresponds to the "default print" i.e.:
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
It seems that the reason the code provided always prints the default range, it's because the lines that determine the printed output are validating the ActiveSheet.Name instead of the value in the "Type of Change field and print"
Solution proposed:
Change these lines to reflect the cell where the "Type of Change field and print" is located:
Replace ActiveSheet.Name with the corresponding cell.address i.e.: F10 and update as required the comparisons against "v1.20" and "v1.21"
If Right(ActiveSheet.Name, 5) = "v1.20" _
Or Right(ActiveSheet.Name, 5) = "v1.21" _
Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
It should become (comparison values shown as a reference, they should be updated in line with the choices in the drop-down list) :
If ActiveSheet.Range("F10").Value2 = "Return from leave" _
Or str = "Corporate" Then
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("H2")
Else
ws.PageSetup.PrintArea = ActiveWorkbook.Worksheets("Form Lists").Range("i2")
End If
Note:
1. Avoid using ActiveWorkbook and ActiveSheet, suggest to replace all instances of them by: ThisWorkbook and datasheet respectively.
2. Additionally, I would suggest to review and incorporate the use of With statement and Select Case statement throughout your procedure.
Very new to VBA and trying to create an automated textfile export.
Currently it works like a charm for row 1 and the textfile is created. But when adding data on row 2 as well I get:
Runtime error 91, Object variable or With block variable not set.
Any help would be much appreciated!
Sub Exportera()
Dim bKlar As Boolean
Dim bSkrivPSlut As Boolean
Dim bSkrivPStart As Boolean
Dim fsoExpFil As FileSystemObject
Dim fsoTextStream2 As TextStream
Dim sExportFile As String
Dim iSvar As Integer
Dim iSvar2 As Integer
Dim sSokvag As String
Dim sFilnamn As String
Dim sTemp As String
Dim sPFalt As String
Dim cVarde As Currency
Dim sDatum As String
'alright då skapar vi fil och skriver till den
Set fsoExpFil = New FileSystemObject
Range("K10").Select
sSokvag = Trim(ActiveCell.FormulaR1C1)
Range("K13").Select
sFilnamn = Trim(ActiveCell.FormulaR1C1)
If Not UCase(Right(sFilnamn, 4)) = ".TXT" Then
sFilnamn = sFilnamn & ".txt"
End If
sExportFile = sSokvag & "\" & sFilnamn
If sSokvag = "" Or sFilnamn = "" Then
MsgBox "Exporten avbryts då sökväg och filnamn saknas för exportfilen.", vbInformation, sAppName
Exit Sub
Else
If fsoExpFil.FileExists(sExportFile) = True Then
iSvar = MsgBox("Filen " & sFilnamn & " finns redan, skall den ersättas?", vbYesNo, sAppName)
If iSvar = vbNo Then
Exit Sub
End If
Else
iSvar = MsgBox("Är du säker att du vill exportera?", vbYesNo, "Exportera")
End If
End If
If iSvar = vbYes Then
Set fsoTextStream2 = fsoExpFil.OpenTextFile(sExportFile, ForWriting, True)
fsoTextStream2.WriteLine "Filhuvud"
fsoTextStream2.WriteLine vbTab & "Typ=" & """Anställda"""
sTemp = "SkapadAv=" & """"
sTemp = sTemp & "Importfil"
sTemp = sTemp & """"
fsoTextStream2.WriteLine vbTab & sTemp
fsoTextStream2.WriteLine vbTab & "DatumTid=" & "#" & Now & "#"
bKlar = False
i = 1
Sheets("Data").Select
While bKlar = False
i = i + 1
Range("A" & i).Select
If Trim(ActiveCell.FormulaR1C1) <> "" Then
If IsNumeric(ActiveCell.FormulaR1C1) Then
fsoTextStream2.WriteLine "PStart"
fsoTextStream2.WriteLine " Typ = ""Anställda"""
Range("A" & i).Select
If Trim(ActiveCell.FormulaR1C1) <> "" Then
fsoTextStream2.WriteLine " Anställningsnummer = " & ActiveCell.FormulaR1C1
End If
Range("B" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Namn=" & Trim(ActiveCell.FormulaR1C1)
End If
Range("D" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Utdelningsadress=" & ActiveCell.FormulaR1C1
End If
Range("E" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " co_adress=" & ActiveCell.FormulaR1C1
End If
Range("G" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Postadress=" & ActiveCell.FormulaR1C1
End If
Range("F" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " Postnummer=" & ActiveCell.FormulaR1C1
End If
Range("C" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sTemp = ActiveCell.FormulaR1C1
sTemp = Mid(sTemp, 1, 6) & "-" & Mid(sTemp, 7)
fsoTextStream2.WriteLine " Personnummer=" & sTemp
End If
Range("H" & i).Select
If Trim(ActiveCell.Text) <> "" Then
fsoTextStream2.WriteLine " E_mail=" & ActiveCell.FormulaR1C1
End If
Range("I" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sTemp = ActiveCell.FormulaR1C1
Range("AM" & i).Select
sTemp = sTemp & ActiveCell.FormulaR1C1
sTemp = Replace(sTemp, "-", "")
fsoTextStream2.WriteLine " Bankkontonummer=" & sTemp
End If
Range("J" & i).Select
If Trim(ActiveCell.Text) <> "" Then
sDatum = ActiveCell.Text
fsoTextStream2.WriteLine " Anställningsdatum=" & "#" & sDatum & "#"
End If
fsoTextStream2.WriteLine "PSlut"
fsoTextStream2.Close
MsgBox "Exporten är klar", vbInformation, sAppName
End If
Else
bKlar = True
End If
Wend
End If
End Sub
Your problem is not exactly what you'd be expecting.
Note that in your while loop, you close your filestream object at the end with fsoTextStream2.Close. What you'll be seeing is that it will successfully write the first line, but then close the file and then try to write to a file that is closed.
Simply moving this outside the loop (after wend) will fix your problem (Shown below).
fsoTextStream2.WriteLine "PSlut"
MsgBox "Exporten är klar", vbInformation, sAppName
End If
Else
bKlar = True
End If
Wend
fsoTextStream2.Close 'This line has been moved outside the loop
End If
End Sub
There's quite a few improvements for your code, if you alter it slightly to avoid .select calls. Also .value rather than .text might be useful if your cells have numeric input. Note that you can extract cell values without having them selected by using range("A" & i).value (or simply range("A" & i)) using worksheet("sheetname").range("A" & i) to access specific sheet cells. (cells(row, column) works just as well).
I'm new to VBA and need get some help with a VLOOKUP?
I keep getting Compile error for Expected: end of statement
This is the line that is giving me problems.
I added the & sign after (row_number) and am now getting a run-time error '9': Subscript out of range error.
Sheets("WIP Count").Range("G" & (row_number)).Formula = "=VLOOKUP(C" & (row_number) & ",PRISM!L:T,8,FALSE)"
Here is the rest of the code.
Sub CommandButton1_Click()
q1_answer = Sheets("Tracker").Range("F8")
q2_answer = Sheets("Tracker").Range("F9")
q3_answer = Sheets("Tracker").Range("F10")
q4_answer = Sheets("Tracker").Range("F11")
If q1_answer = "" Then
MsgBox "Fill in Name"
Exit Sub
End If
If q2_answer = "" Then
MsgBox "Fill in Serial Number"
Exit Sub
End If
If q3_answer = "" Then
MsgBox "Fill in Part Number"
Exit Sub
End If
If q4_answer = "" Then
MsgBox "Fill in Quantity"
Exit Sub
End If
row_number = 1
Do
DoEvents
row_number = row_number + 1
item_in_review = Sheets("WIP_Count").Range("A" & row_number)
Loop Until item_in_review = ""
last_transaction_id = Sheets("WIP_Count").Range("A" & (row_number - 1))
Dim next_transaction_id As Integer
next_transaction_id = last_transaction_id + 1
Sheets("WIP_Count").Range("A" & (row_number)) = next_transaction_id
Sheets("WIP_Count").Range("B" & (row_number)) = q1_answer
Sheets("WIP_Count").Range("C" & (row_number)) = q2_answer
Sheets("WIP_Count").Range("D" & (row_number)) = q3_answer
Sheets("WIP_Count").Range("E" & (row_number)) = q4_answer
Sheets("WIP_Count").Range("F" & (row_number)).Value = Date
Sheets("WIP Count").Range("G" & (row_number)).Formula = "=VLOOKUP(C" & (row_number) & ",PRISM!L:T,8,FALSE)"
Sheets("Tracker").Range("F8") = ""
Sheets("Tracker").Range("F9") = ""
Sheets("Tracker").Range("F10") = ""
Sheets("Tracker").Range("F11") = ""
MsgBox "Done"
End Sub