How to format the body of email - excel

We run an SQL query and paste the results in sheet1,
then transpose the results data to sheet2, then email sheet2 data to someone.
I’ve written the vba code for the above task but im not getting these required results:
Line break is not need like in the below screenshot
Need to remove space vbtab between two sentences in email body
Format of the email should in plain text
Is there any possibility for running an SQL query automatically through VBA code? If yes please suggest.
Below is my code
Option Explicit
Sub sendemail_excel()
Sheet2.Cells.Clear
Worksheets("sheet1").Activate
Range("A1").Activate
Do Until ActiveCell.Value = ""
Sheet1.Activate
ActiveCell.Offset(1, 0).Select
Range(ActiveCell, ActiveCell.End(xlToRight)).Copy
Worksheets("Sheet2").Activate
Range("B" & Rows.Count).End(xlUp).Select
ActiveCell.Offset(2, 0).PasteSpecial xlPasteValues, xlPasteSpecialOperationNone, Transpose:=True, skipblanks:=True
'ActiveCell.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone, Transpose:=True, skipblanks:=True
'ActiveCell.Offset(1, 0).Activate
'Range("B1").Select
'ActiveCell.End(xlDown).Activate
'ActiveCell.Offset(2, 0).Activate
Range("B" & Rows.Count).End(xlUp).Offset(-2, 0).NumberFormat = "M/D/YYYY H:MM:SS AM/PM"
Range("B" & Rows.Count).End(xlUp).Select
ActiveCell.Offset(-4, -1).Value = "FEEDFILENAME="
ActiveCell.Offset(-3, -1).Value = "RECIPIENT="
ActiveCell.Offset(-2, -1).Value = "PROCESSEDTIME="
ActiveCell.Offset(-1, -1).Value = "PROCESSSTATUS="
ActiveCell.Offset(0, -1).Value = "NUMBEROFROWS="
Worksheets("sheet1").Activate
Loop
Columns.AutoFit
Range("B:B").HorizontalAlignment = xlLeft
Application.ScreenUpdating = False
Application.CutCopyMode = False
Range("B" & Rows.Count).End(xlUp).Select
ActiveCell.Select^
Range(Selection, Cells(3, 1)).HorizontalAlignment = xlLeft
Sheet2.Activate
Range("B" & Rows.Count).End(xlUp).Select
ActiveCell.Select
Range(Selection, Cells(3, 1)).Select
ActiveWorkbook.EnvelopeVisible = True
With ActiveSheet.MailEnvelope
.Introduction = "Hi abc Team - This is the confirmation mail regarding the files, which xyz" & " " & Date - 1
.Item.To = "chinnolamanohar#gmail.com"
.Item.CC = "chinnolamanohar#gmail.com"
.Item.Subject = "Confirmation for earnings feed from abc equity research to xyz"
.Item.Send
End With
End Sub

You can run queries directly against a database, lots of documentation online.
Your connection string will vary on database type - MSSQL, MySQL etc.
Accessing SQL Database in Excel-VBA
https://www.ptr.co.uk/blog/using-excel-vba-query-sql-server-database

Related

else if statement for check in check out sheet vba not working

I have an excel sheet in which lies a data entry form and a check in check out list. I have a macro set up to search for the entry, and if it doesnt exist, make a new entry with a checkout time, if it does exist, it checks it back in with a time. My issue lies when I try to check out an entry that already exists. The code just updates the check in time. Ive added an elseif statement into the code but it doesnt seem to do anything. If anyone could help me figure out why itd be much appreciated.
Sub inout()
Dim barcode As String
Dim rng As Range
Dim rownumber As Long
barcode = Worksheets("Sheet1").Cells(2, 2)
Set rng = Sheet1.Columns("a:a").Find(What:=barcode, _
LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If rng = True Or ActiveCell.Offset(0, 2).Value = True Then
rownumber = rng.Row
Worksheets("Sheet1").Cells(rownumber, 1).Select
ActiveCell.Offset(0, 2).Clear
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Date & " " & Time
ActiveCell.NumberFormat = "m/d/yyyy h:mm AM/PM"
Worksheets("Sheet1").Cells(2, 2) = ""
Cells(2, 2).Select
ElseIf rng Is Nothing Then
ActiveSheet.Columns("a:a").Find("").Select
ActiveCell.Value = barcode
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Date & " " & Time
ActiveCell.NumberFormat = "m/d/yyyy h:mm AM/PM"
Worksheets("Sheet1").Cells(2, 2) = ""
ActiveCell.Offset(0, 3).Select
ElseIf rng = True Then
rownumber = rng.Row
Worksheets("Sheet1").Cells(rownumber, 1).Select
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = Date & " " & Time
ActiveCell.NumberFormat = "m/d/yyyy h:mm AM/PM"
Worksheets("Sheet1").Cells(2, 2) = ""
rng.Offset(, 1).Clear
ActiveCell.Offset(0, 2).Value = "TOOL CRIB"
Cells(2, 2).Select
End If
End Sub

I can't convert data into appropriate format

I created auto-populating offset function to add data into my list. Now I need to convert the inserted data into the same format as cells above. I reckon there is some shorter code to do this. Mine's not working anyway. The data are scattered all over the worksheet.
Option Explicit
Sub data_entry()
Application.ScreenUpdating = False
Dim ItemNumber As String
Dim ItemType As String
Dim Issues As String
Dim InventoryValue As String
ItemNumber = InputBox("Please enter Item Number", "Item Number", "Type here")
ItemType = InputBox("Please enter Item Type", "Item Type", "Type here")
Issues = InputBox("Please enter Number of Issues", "Issues", "Type here")
InventoryValue = InputBox("Please enter Inventory Value", "Inventory Value", "Type here")
Range("A2").Activate
Do
If ActiveCell.Value = "" Then Exit Do
ActiveCell.Offset(1, 0).Activate
Loop
ActiveCell.Value = ItemNumber
'ActiveCell.Offset(-1, 0).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
ActiveCell.Offset(0, 5).Value = ItemType
'ActiveCell.Offset(-1, 0).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
ActiveCell.Offset(0, 7).Value = Issues
'ActiveCell.Offset(-1, 7).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
ActiveCell.Offset(0, 8).Value = InventoryValue
'ActiveCell.Offset(-1, 8).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
End Sub
I believe the following will achieve your expected results without Activating a cell and without the Do Loop too, both of which will invariably result in reduced performance:
Sub Data_Entry()
Dim ws As Worksheet: Set ws = ThisWorkbook.ActiveSheet 'or you could be more explicit and use: ThisWorkbook.Worksheets("Sheet1")
'declare and set the worksheet being used, amend as required.
Application.ScreenUpdating = False
Dim ItemNumber As String
Dim ItemType As String
Dim Issues As String
Dim InventoryValue As String
ItemNumber = InputBox("Please enter Item Number", "Item Number", "Type here")
ItemType = InputBox("Please enter Item Type", "Item Type", "Type here")
Issues = InputBox("Please enter Number of Issues", "Issues", "Type here")
InventoryValue = InputBox("Please enter Inventory Value", "Inventory Value", "Type here")
NextRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
'find the next free row in Column A
ws.Range("A" & NextRow).Value = ItemNumber
'another way to reference a cell would be: ws.Cells(NextRow, 1).Value = ItemNumber
ws.Range("F" & NextRow).Value = ItemType
ws.Range("H" & NextRow).Value = Issues
ws.Range("I" & NextRow).Value = InventoryValue
ws.Range("A" & NextRow - 1 & ":I" & NextRow - 1).Copy
'Copy above row from Columns A to I
ws.Range("A" & NextRow & ":I" & NextRow).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
'paste the formating to new row Columns A to I
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
Give this a try :
Option Explicit
Sub data_entry()
Application.ScreenUpdating = False
Dim ItemNumber As String
Dim ItemType As String
Dim Issues As String
Dim InventoryValue As String
ItemNumber = InputBox("Please enter Item Number", "Item Number", "Type here")
ItemType = InputBox("Please enter Item Type", "Item Type", "Type here")
Issues = InputBox("Please enter Number of Issues", "Issues", "Type here")
InventoryValue = InputBox("Please enter Inventory Value", "Inventory Value", "Type here")
Range("A2").Activate
Do
If ActiveCell.Value = "" Then Exit Do
ActiveCell.Offset(1, 0).Activate
Loop
ActiveCell.Value = ItemNumber
'ActiveCell.Offset(-1, 0).Copy
Range(ActiveCell, ActiveCell.Offset(-1, 0)).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial xlPasteValuesAndNumberFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial PasteSpecial xlPasteFormats
ActiveCell.Offset(0, 5).Value = ItemType
'ActiveCell.Offset(0, 5).Copy
Range(ActiveCell, ActiveCell.Offset(-1, 0)).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial xlPasteValuesAndNumberFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial PasteSpecial xlPasteFormats
ActiveCell.Offset(0, 7).Value = Issues
'ActiveCell.Offset(-1, 7).Copy
Range(ActiveCell, ActiveCell.Offset(-1, 7)).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial xlPasteValuesAndNumberFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial PasteSpecial xlPasteFormats
ActiveCell.Offset(0, 8).Value = InventoryValue
'ActiveCell.Offset(-1, 8).Copy
Range(ActiveCell, ActiveCell.Offset(-1, 8)).Copy
'ActiveCell.Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial xlPasteValuesAndNumberFormats
Sheets("NameSheet").Range(ActiveCell, ActiveCell.Offset(1, 0)).PasteSpecial PasteSpecial xlPasteFormats
End Sub

VBA: Call a Macro with a Variable

I'm a beginner in VBA and i have done a script which would call different macros according to the sheet name which is assigned to a variable SheetName. I'm trying to execute the below code and I'm getting a Compile Error. Hope you guys can help me!!
Sub ScrubeCareOutput()
Dim SheetName, Header, PolicyNumber As String
Dim CheckPoint As Integer
StartTime = Now()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Sheets("ConsolidatedData").Select
Range("P:P").Cut
Range("A1").Select
ActiveCell.EntireColumn.Insert
Range("A1").Select
'Deleting old sheet
Application.StatusBar = "Calculating Loop .."
Sheets("Reference").Select
Range("L2").Select
ActiveCell.Offset(1, 0).Select
SheetName = ActiveCell.Value
'Scrubbing Output
Do Until SheetName = ""
Application.StatusBar = "Scrubbing " & SheetName & " Output.."
Sheets(SheetName).Select
Range("a1").Select
If IsEmpty(Range("A2")) = False Then
Range("A2").Select
Header = ActiveCell.Value
End If
'Deleting Headers
Selection.AutoFilter Field:=1, Criteria1:=Header
ActiveSheet.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
ActiveSheet.AutoFilterMode = False
Selection.AutoFilter Field:=1, Criteria1:=""
ActiveSheet.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
ActiveSheet.AutoFilterMode = False
Selection.AutoFilter Field:=1, Criteria1:="©Copyright Nebo Systems, Inc."
ActiveSheet.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
ActiveSheet.AutoFilterMode = False
Selection.AutoFilter Field:=1, Criteria1:="Powered by ECARE?"
ActiveSheet.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
ActiveSheet.AutoFilterMode = False
Range("1:1").Delete
'Scrubbing Data
Call SheetName
'Creating fields
For i = 1 To 4
ActiveCell.EntireColumn.Insert
Next
Range("A1").Select
ActiveCell.Value = "Account Number"
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = "Mnemonic"
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = "Begin Date"
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = "End Date"
'Formulating data
ActiveCell.Offset(1, -3).Select
ActiveCell.Value = "=VLOOKUP(E2,ConsolidatedData!$A:$S,3,0)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = "=VLOOKUP(E2,ConsolidatedData!$A:$S,16,0)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = "=VLOOKUP(E2,ConsolidatedData!$A:$S,17,0)"
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = "=VLOOKUP(E2,ConsolidatedData!$A:$S,18,0)"
ActiveCell.Offset(0, 1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, -4).Select
Range(Selection, Selection.End(xlUp)).Select
Range(Selection, Selection.Offset(0, 3)).Select
Selection.FillDown
Selection.Copy
Selection.PasteSpecial xlPasteValues
Range("a1").Select
'Formatting data
Application.StatusBar = "Formatting " & SheetName & " Output.."
With ActiveSheet
.Cells.Font.Name = "Calibri"
.Cells.Font.Size = "10"
End With
Range("1:1").Select
Selection.Font.Bold = True
Range("A1").Select
'Save data
ActiveWorkbook.Saved = True
Sheets("Reference").Select
ActiveCell.Offset(1, 0).Select
SheetName = ActiveCell.Value
Else
Sheets("Reference").Select
ActiveCell.Offset(1, 0).Select
SheetName = ActiveCell.Value
End If
Loop
Sheets("UB92Monitor").Select
'Confirmation message
ActiveWorkbook.Save
EndTime = Format((Now() - StartTime), "HH:MM:SS")
Application.StatusBar = False
MsgBox "Data scrubbed successfully in " & EndTime, vbOKOnly, "Data Scrubbing Status"
End Sub

Find The Max Value And From A Column That Also Contains Text

I'm trying to create a macro that would find the maximum numerical value in a column (which also contains text) and inserts a new row with that value +1.
For some reason it won't work and just keeps the original number, it also messes up the conditional formatting I have in column D even if that column is locked.
Sub_Move()
Set wk1 = Sheet1
Set wk2 = Sheet4
Set wk3 = Sheet5
Dim mynumber As Long
Application.ScreenUpdating = False
Sheet1.Unprotect
Sheet4.Unprotect
Sheet5.Unprotect
mynumber = 1
'Move-Characterisation'
Worksheets("Characterisation").Activate
For i = 1000 To 15 Step -1
If Range("W" & i).Value = "Completed" Then
Worksheets("Burn").Activate
Range("B15:W15").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("B15:W15").Interior.ColorIndex = xlNone
End If
Worksheets("Characterisation").Activate
If Range("W" & i).Value = "Completed" Then
Range("W" & i).Select
Range("W" & i).Value = "Delete"
Range(ActiveCell, ActiveCell.Offset(0, -21)).Select
Selection.Copy
Worksheets("Burn").Activate
Range("B15").Select
ActiveSheet.Paste
Range("W15").ClearContents
**MaxVal1 = Application.WorksheetFunction.Max(wk2.Range("D15:D1000"))
Range("D15").Value = MaxVal1 + 1**
End If
Worksheets("Characterisation").Activate
If Range("W" & i).Value = "Delete" Then
Range("W" & i).Select
Range(ActiveCell, ActiveCell.Offset(0, -21)).Select
Selection.Delete Shift:=xlUp
End If
Next
I would be grateful for any help.

Error 13: Type Mismatch Row Limit Restriction?

When the excel sheet raw data has under 10,000 rows it runs, when it has 10,000 rows and over I get the error. Any idea? The error is pointed to the mu = Cells(joker, 12)
Columns("A:I").Select
Selection.ClearContents
Windows("New Registrations.xls").Activate
ActiveWindow.WindowState = xlNormal
Columns("A:I").Select
Selection.Copy
Windows("Polk Trend Report CYTD.xlsm").Activate
Range("A1").Select
ActiveSheet.Paste
Selection.Interior.ColorIndex = xlNone
Selection.Font.ColorIndex = 0
Sheets("Data").Select
Dim nz As Long
Dim joker As Long
Dim lambda As Long
nz = Cells(4, 12).Value
Dim mu As Long
For joker = 5 To nz + 4
lambda = Cells(joker, 11)
mu = Cells(joker, 12)
If lambda <> 0 And mu - lambda > 1 Then
Range("A" & lambda).Select
Selection.Copy
Range("A" & lambda + 1 & ":A" & mu - 1).Select
ActiveSheet.Paste
Else:
End If
Next joker
Range("N5:O" & nz + 4).Select
Selection.ClearContents
Dim iota As Long
Dim kappa As Long
iota = 7
Do While Cells(iota, 2).Value <> ""
If Cells(iota, 2) = "UNKNOWN" Then
kappa = Application.WorksheetFunction.Match(Cells(iota, 1).Value, Range("J1:J" & nz + 4), 0)
Cells(kappa, 14).Value = Cells(iota, 7).Value
Cells(kappa, 15).Value = Cells(iota, 5).Value
Range("A" & iota & ":I" & iota).Select
Selection.Delete Shift:=xlUp
iota = iota - 1
ElseIf Cells(iota, 2) = "Zone Total" Then
Range("A" & iota & ":I" & iota).Select
Selection.Delete Shift:=xlUp
iota = iota - 1
ElseIf Application.WorksheetFunction.And(Cells(iota, 5) = 0, Cells(iota, 7) = 0) Then
Range("A" & iota & ":I" & iota).Select
Selection.Delete Shift:=xlUp
iota = iota - 1
Else:
End If
iota = iota + 1
Loop
Range("A" & iota & ":I" & iota).Select
Selection.Delete Shift:=xlUp
Range("C5:I5").Select
Selection.Copy
Range("C6").Select
ActiveSheet.Paste
Set pvtTable = Worksheets("Total Dealer (Trend)").Range("O5").PivotTable
pvtTable.RefreshTable
Sheets("Total Dealer (Trend)").Select
Cells.Select
Selection.Columns.AutoFit
Sheets("Data").Select
Range("S40:T" & nz + 39).Select
Selection.Copy
Range("A2").Select
Sheets("Total Dealer (Trend)").Select
Range("B40").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Sheets("Data").Select
Range("U40:U" & nz + 39).Select
Selection.Copy
Range("A2").Select
Sheets("Total Dealer (Trend)").Select
Range("E40").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Range("B40:E" & nz + 39).Select
Selection.Sort Key1:=Range("E40"), Order1:=xlDescending, Header:=xlNo _
, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Range("A1").Select
ActiveWindow.WindowState = xlMaximized
End Sub
I think you might have a format change taking place on your Worksheet after row 10,000. Say it was a date, now it's General or some other type conflict, and you are getting a data mismatch as a result of the Value of mu being set by
"L10000"
Check the format of the cells below 10,000. Especially Column "L"
this is an example error handler, hopefully you can just copy and paste this into your code as described and it should output the value of the failing cell when the error occurs, and then you can hopefully correct it. The following goes right at the top of your code
On Error GoTo MyProcedure_Error
Then the below goes above the end sub
MyProcedure_Exit:
On Error GoTo 0
Exit Sub
MyProcedure_Error:
Select Case Err.Number
'the "Case 9" statement below is left as an example to show how you could code a
'specific error message if a specifc module needed it
'Case 9
'MsgBox "The input file does not appear to be in the correct format, for importing into the " & _
'" Locations tab" & vbCrLf & "The expected format is " & Str(Import_Cols) & " columns, Pipe Delimited" & _
'vbCrLf, vbCritical, "Error in in procedure TrimColumn of Module DeveloperToolKit"
Case Else
MsgBox "An unexpected error has occured, the call value that has failed is." & _
vbCrLf & Cells(joker, 12) & _
vbCrLf & "Error Code = " & Str$(Err.Number) & _
vbCrLf & "Error Text = " & Err.Description, vbCritical, "Critical Error"
End Select
Resume MyProcedure_Exit

Resources