Hide excel columns doesn't work in outlook vba - excel

I simply can't find a way to hide specific columns in outlook vba. I tried everything. My current code is the following:
Sub ExportToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim enviro As String
Dim strPath As String
Dim ns As NameSpace
Dim item As Object
Dim inbox As MAPIFolder
Dim i As Long
Dim j As Long
' Get Excel set up
enviro = CStr(Environ("USERPROFILE"))
'the path of the workbook
strPath = enviro & "\Documents\test.xlsx"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
' Process the message record
`On Error Resume Next
For j = 2 To 367
If xlSheet.cells(1, j).Value <> Date And xlSheet.cells(1, j).Interior.ColorIndex = 4 Then
xlSheet.Columns(j).Interior.ColorIndex = 0
End If
If xlSheet.cells(1, j).Value = Date Then
xlSheet.Columns(j).Interior.ColorIndex = 4
For i = 2 To j - 1
xlSheet.Columns(i).EntireColumn.Hidden = True
Debug.Print xlSheet.cells(1, i).Value
Next i
Exit For
End If
Next j
xlWB.Worksheets("Sheet1").Columns("A:NB").EntireColumn.AutoFit
xlWB.Close 1
If bXStarted Then
xlApp.Quit
End If
End Sub
The 1st row, starting from the 2nd column of my excel sheet is populated with dates starting from 01.01.2017 and up to 31.12.2017.
I want the macro to hide all dates from before the current day.
As you can see, the debug.print in the test for hiding works as intended and prints all dates from 01.01.2017 to current date-1.
As a side note, xlSheet.Columns(i).Color = 5287936 did not work either.
By placing the On Error Resume Next from before the for in comments, I get an "Application-defined or object-defined error" error.
If I remove all the error tests, I get an "ActiveX component can't create object" error.
New finding, if I debug.print xlsheet.columns(i).hidden I get a "true" message in the immediate window. Apparently the code does exactly what it's supposed to, but it just doesn't take effect.

Try Autofit manually. You should find it unhides hidden columns.
Move Autofit so it is before the columns are hidden or be more precise about the columns to autofit.
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
xlWB.Worksheets("Sheet1").Columns("A:NB").EntireColumn.AutoFit
' Process the message record
For j = 2 To 367
If xlSheet.Cells(1, j).Value <> Date And xlSheet.Cells(1, j).Interior.ColorIndex = 4 Then
xlSheet.Columns(j).Interior.ColorIndex = 0
End If
If xlSheet.Cells(1, j).Value <> Date And xlSheet.Cells(1, j).Interior.ColorIndex <> 0 Then
xlSheet.Columns(j).Interior.ColorIndex = 4
End If
If xlSheet.Cells(1, j).Value = Date Then
xlSheet.Columns(j).Interior.ColorIndex = 4
For i = 2 To j - 1
xlSheet.Columns(i).EntireColumn.Hidden = True
Debug.Print xlSheet.Cells(1, i).Value
Next i
Exit For
End If
Next j

Related

Excel.Application not closed excel file

I want to read some data from excel file and close it.
but my code not closed it:
Function getColumnOfFirstRow(PATH, size) As Long
Dim oApp_Excel As Excel.Application
Dim oBook As Excel.Workbook
Dim column As Long
column = 0
Set oApp_Excel = CreateObject("EXCEL.APPLICATION")
oApp_Excel.DisplayAlerts = False
oApp_Excel.Visible = True
Set oBook = oApp_Excel.Workbooks.Open(PATH, ReadOnly:=True)
On Error GoTo errhand
column = oBook.Sheets("Sheet1").Cells.Find(What:=CStr(size)).column
oBook.Close True
oApp_Excel.Quit
Set oBook = Nothing
errhand:
Select Case Err.Number
Case 91
column = 0
End Select
getColumnOfFirstRow = column
End Function
I think this part of my code must close it:
oBook.Close True
oApp_Excel.Quit
Using a New Instance of Excel
It looks like overkill to open and close Excel and a workbook to just retrieve a number but let's say we're practicing handling objects and error handling.
Function GetSizeColumn(ByVal Path As String, ByVal Size As Double) As Long
On Error GoTo ClearError
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
xlApp.Visible = True ' out-comment when done testing
Dim wb As Excel.Workbook
Set wb = xlApp.Workbooks.Open(Path, True, True)
Dim SizeColumn As Long
SizeColumn = wb.Sheets("Sheet1").Rows(1).Find(CStr(Size)).Column
' You can avoid the expected error as you have learned in your newer post.
' In this case, if the error occurs, the function will end up with
' its initial value 0 since its result is declared 'As Long'
' i.e. the following line will never be executed.
GetSizeColumn = SizeColumn
ProcExit:
On Error Resume Next
If Not wb Is Nothing Then wb.Close False
If Not xlApp Is Nothing Then xlApp.Quit
On Error GoTo 0
Exit Function
ClearError:
Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description
Resume ProcExit
End Function
Try it. 100% working code about creating the excel. In this code, excel converts recordset in excel successfully. After that close the excel successfully. No error.
Also, check with the Task manager and close any excel file open in the process.
Public Sub ConvertRecordSetToExcelFull(Rs As Recordset, _
FileNameWithPath As String, _
SheetName As String, _
Rangename As String)
On Error GoTo Error1
Dim ExlFile As Object, Book As Object, Sheet As Object, K As Long, J As Long
Set ExlFile = CreateObject("Excel.Application")
Set Book = ExlFile.Workbooks.Add
Set Sheet = Book.Worksheets(1)
ExlFile.DisplayAlerts = False
K = 1
For J = 0 To Rs.Fields.Count - 1
Sheet.Cells(K, J + 1) = UCase(Rs.Fields(J).Name)
Next
K = K + 1
If Rs.RecordCount >= 1 Then
'Call RecCount(rs)
Do While Rs.EOF <> True
For J = 0 To Rs.Fields.Count - 1
Sheet.Cells(K, J + 1) = Rs.Fields(J)
Next
K = K + 1
Rs.MoveNext
Loop
End If
Book.Worksheets(1).Name = SheetName
Book.SaveAs FileNameWithPath
ExlFile.ActiveWorkbook.Close False
ExlFile.Quit
Set Sheet = Nothing
Set ExlFile = Nothing
Screen.MousePointer = vbNormal
Exit Sub
Error1:
MsgBox Err.Description
Err.Clear
End Sub

VBA convert embedded excel sheet to word table in word file

I need to convert the embedded excel sheet object to word table in word file, I am currently using is to open the embedded excel sheet object , select the content and paste to word. Could there be a better way to simplify this action?
I try to create a mirco but .OLEformat keep error and said this member cannot be accessed on a horizontal line.
Sub ConvertXLObjs()
Application.WindowState = wdWindowStateMinimize
Dim i As Long, j As Long, k As Long, Rng As Range, bDel As Boolean
Dim objOLE As Word.OLEFormat, objXL As Object
With ActiveDocument
For i = .InlineShapes.Count To 1 Step -1
With .InlineShapes(i)
If Not .OLEFormat Is Nothing Then
If Split(.OLEFormat.ClassType, ".")(0) = "Excel" Then
Set Rng = .Range
Set objOLE = .OLEFormat
objOLE.Activate
Set objXL = objOLE.Object
With objXL.ActiveSheet
.Range("$A$1:" & _
.Cells.SpecialCells(11).Address).Copy ' 11 = xlCellTypeLastCell
End With
objXL.Application.Undo
.Delete
With Rng
.Characters.First.PasteAndFormat wdTableInsertAsRows
.MoveEnd wdParagraph, 2
With .Tables(1)
.AllowAutoFit = False
.BottomPadding = 0
.LeftPadding = 0
.RightPadding = 0
.TopPadding = 0
.Rows.AllowBreakAcrossPages = False
.Rows.HeightRule = wdRowHeightExactly
If .Uniform = True Then
For j = .Columns.Count To 1 Step -1
bDel = True
For k = 1 To .Columns(j).Cells.Count
If Len(.Columns(j).Cells(k).Range.Text) > 2 Then
bDel = False
Exit For
End If
Next
If bDel = True Then
.Columns(j).Delete
Else
Exit For
End If
Next
End If
End With
End With
End If
End If
End With
Next
End With
Set objXL = Nothing: Set objXL = Nothing: Set Rng = Nothing
Application.WindowState = wdWindowStateNormal
MsgBox "Finished processing!"
End Sub
the code is refer from https://social.msdn.microsoft.com/Forums/office/en-US/5955da06-725d-45f2-aa1b-5eb37c0646c6/how-to-convert-all-embeded-excel-sheets-in-word-into-words-tables?forum=worddev
Example:

VBA Loop to Extract data from Excel into Word

I have already spent too many hours looking for the right answer and every which way I try it doesn't work the way I want it to.
I receive the "Application or Object defined error" referencing the Excel file when I run the following. It compiles just fine, so I am not sure where I went wrong. I need it to pull data from two different places on an Excel sheet, place them in specific defined labels in a Word doc, save it with custom name and continue to do so until the end of the list in Excel. Data begins in A1 and B1 respectively.
Dim oXL As Object
Dim oWB As Object
Dim exWb As String
Dim oSheet As Object
Dim bStartExcel As Boolean
Dim objDoc As Object
Dim fcount As Long
Dim iRow As Integer
exWb = "C:\Documents\Waivers_needed_0926_Take2.xlsx"
On Error Resume Next
'If Excel running use it
Set oXL = GetObject(, "Excel.application")
If Err.Number <> 0 Then 'If Excel isn't running then start it
bStartExcel = True
Set oXL = CreateObject("Excel.Application")
End If
On Error GoTo Err_Handler
'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=exWb)
'Process the worksheet
Set oSheet = oXL.ActiveWorkbook.Worksheets(4)
For iRow = 1 to 100
With oSheet.Cells(iRow, 0)
ActiveDocument.Amt_Paid.Caption = .Value
End With
With oSheet.Cells(iRow, 1)
ActiveDocument.Payee.Caption = .Value
End With
'Save Word Document with new name
fcount = fcount + 1
With ActiveDocument
.SaveAs FileName:="C:\Documents\Waivers\" & Split(ActiveDocument.Name, ".")(0) & "_" & Format(Now(), "YYYYMMDD") & "_" & fcount & ".doc"
End With
Next iRow
Exit Sub

How to extract email message and fill spreadsheet with values

I have a macro that reads the unread messages in my inbox and extracts the data from the message with a delimiter of ":" . In the loop I want to be able to load the new excel spreadsheet with the values from the message.
I am able to select the first cell and save the data but it is getting over written. each time in the loop I want the data to go to the next cell in the column that is empty instead of overwriting the same cell.
Here is my code so far...
Public Sub Application_NewMail()
Dim newbk As Workbook
Set newbk = Workbooks.Add
newbk.SaveAs "C:\Users\RickG\Desktop\test2.xlsx" 'other parameters can be set here if required
' perform operations on newbk
newbk.Close savechanges:=True
Dim ns As Outlook.NameSpace
Dim InBoxFolder As MAPIFolder
Dim InBoxItem As Object 'MailItem
Dim Contents As String, Delimiter As String
Dim Prop, Result
Dim i As Long, j As Long, k As Long
'Setup an array with all properties that can be found in the mail
Prop = Array("Name", "Email", "Phone", "Customer Type", _
"Message")
'The delimiter after the property
Delimiter = ":"
Set ns = Session.Application.GetNamespace("MAPI")
'Access the inbox folder
Set InBoxFolder = ns.GetDefaultFolder(olFolderInbox)
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim ws As Worksheet
Set xlApp = New Excel.Application
With xlApp
.Visible = False
Set xlWB = .Workbooks.Open("C:\Users\RickG\Desktop\test2.xlsx", , False)
Set ws = .Worksheets("Sheet1")
End With
Dim LR As Long
For Each InBoxItem In InBoxFolder.Items
'Only process mails
If Not TypeOf InBoxItem Is MailItem Then GoTo SkipItem
'Skip wrong subjects
If InStr(1, InBoxItem.Subject, "FW: New Lead - Consumer - Help with Medical Bills", vbTextCompare) = 0 Then GoTo SkipItem
'Already processed?
If Not InBoxItem.UnRead Then GoTo SkipItem
'Mark as read
InBoxItem.UnRead = False
'Get the body
Contents = InBoxItem.Body
'Create space for the result
ReDim Result(LBound(Prop) To UBound(Prop)) As String
'Search each property
i = 1
For k = LBound(Prop) To UBound(Prop)
'Find the property (after the last position)
i = InStr(i, Contents, Prop(k), vbTextCompare)
If i = 0 Then GoTo NextProp
'Find the delimiter after the property
i = InStr(i, Contents, Delimiter)
If i = 0 Then GoTo NextProp
'Find the end of this line
j = InStr(i, Contents, vbCr)
If j = 0 Then GoTo NextProp
'Store the related part
Result(k) = Trim$(Mid$(Contents, i + Len(Delimiter), j - i - Len(Delimiter)))
'for every row, find the first blank cell and select it
'MsgBox Result(k)
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("A" & LR).Value = Result(k)
'Update the position
i = j
NextProp:
Next
xlApp.DisplayAlerts = False
xlWB.SaveAs ("C:\Users\RickG\Desktop\test2.xlsx")
xlWB.Close
xlApp.Quit
If MsgBox(Join(Result, vbCrLf), vbOKCancel, "Auto Check In") = vbCancel Then Exit Sub
SkipItem:
Next
End Sub
You're not tracking your loop correctly. If you change
Range("A" & LR).Value = Result(k)
to
Range("A" & LR + 1).Value = Result(k)
in your
For k = LBound(Prop) To UBound(Prop)
loop, that should correct your issue.
EDIT: Sorry, findwindow. I didn't see the comment thread below the question. I just saw that the question had no answer yet.

Method (everything) of object Global failed

I have a macro which takes the body of an email, splits it into an array and places it into excel. It then uses colons to split rows into [label] and [data].
For some reason it has stopped working. I had some good help here but it has now failed in the second subroutine and I can't get my head around the error. I am sure it's something simple, possibly related to running from outlook or incorrect definition of ranges. Everything using rows, cells, range object etc gives this error.
The exact error is Runtime 1004 error. Method [cells, rows] of object Global failed
I have used a comment to mark the point where problems begin:
Private oXLApp As Object, oXLWb As Object, oXLWs As Object
Sub Thermo_to_excel()
Dim myOlApp As Object, mynamespace As Object
Dim ThermoMail As Object
Dim msgText, delimtedMessage, Delim1 As String
Set myOlApp = Outlook.Application
Set mynamespace = myOlApp.GetNamespace("mapi")
Set ThermoMail = Application.ActiveInspector.CurrentItem
delimtedMessage = ThermoMail.Body
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
Set oXLWb = oXLApp.Workbooks.Add
Set oXLWs = oXLWb.Sheets("Sheet1")
'Truncated [Array definition goes here]
With oXLWs
.Range(.Cells(1, 1), .Cells(lastRow, 1)).Value = _
oXLApp.WorksheetFunction.Transpose(messageArray)
End With
Call splitAtColons
ThermoMail.Close (olDiscard)
End Sub
Sub splitAtColons()
Dim Roows As Integer
'PROBLEMS start here now
Roows = Cells(oXLWs.Rows.Count & "," & oXLWs.ActiveCell.Column).End(xlUp).Row
Range("A1").Select
Range("A1:B" & Roows).Font.Name = Range("B1").Font.Name
Range("A1:B" & Roows).NumberFormat = "#"
'Application.ScreenUpdating = False
Do Until Z = Roows
If Not InStr(ActiveCell.Value, ":") = 0 Then
Cells(ActiveCell.Row, 2).Value = Trim(Mid(ActiveCell.Value, InStr(ActiveCell.Value, ":") + 1))
ActiveCell.Value = Left(ActiveCell.Value, InStr(ActiveCell.Value, ":"))
Else
Cells(ActiveCell.Row, 2).Value = Trim(ActiveCell.Value)
ActiveCell.Value = ""
End If
If ActiveCell.Value = "" And Range("B" & ActiveCell.Row).Value = "" Then
ActiveCell.EntireRow.Delete
Roows = Roows - 1
Z = Z - 1
End If
Range("A" & Z + 2).Select
Z = Z + 1
Loop
Columns("B:B").EntireColumn.AutoFit
Columns("A:A").EntireColumn.AutoFit
'Application.ScreenUpdating = True
End Sub
I believe your problem is that you are not fully defining your Range, Cells, & Columns functions. Try adding oXLWs. before each of those functions, or add a With oXLWs line and add . before each of those functions and see what happens.
If you run this in Excel, the Range, Cells, & Columns functions will work because they will refer to the active worksheet. If you run this through Outlook, it may not work if the sheet is not active.

Resources