Resizing OLEobject custom icon - vba

I have code to insert pdf invoice copies in customer's account statement. The code is working fine. Just the custom icon size is not as per the defined 15x51 (HxW). Please suggest how the code can resize the icon file to fit in this 15x51 box (the size of cells in column M as in below picture)? I am using a 16x16 icon file.
Here is the current result.
Sub Insert_PDF_File()
Application.ScreenUpdating = False
Dim cell As Range
' loop each cell in column A
For Each cell In Range("A10:A" & Range("A" & Rows.Count).End(xlUp).Row)
' make sure the cell is NOT empty before doing any work
If Not IsEmpty(cell) Then
' create and insert a new OleObject based on the path
Dim ol As OLEObject
' ActiveWorkbook.path & "\" & cell & ".pdf" will make the filename
Set ol = ActiveSheet.OLEObjects.Add( _
Filename:="C:\Invoices\Renamed" & "\" & cell & ".pdf", _
Link:=False, _
DisplayAsIcon:=True, _
IconFileName:="C:\Users\pvishwas\Documents\WORK\Macros\PDF.ico", _
IconIndex:=0, _
Height:=15, Width:=51, IconLabel:="Open")
' align the OleObject with Column D - (0 rows, 3 columns to the right from column A)
With ol
.Top = cell.Offset(0, 12).Top
.Left = cell.Offset(0, 12).Left
End With
End If
Next
Application.ScreenUpdating = True
End Sub

According to me, it's due to icon size.
Please check below the code I created. It takes given size for object.
Sub AddPDF()
Dim ws As Worksheet
Dim FilePath As String
Dim x As OLEObject
Set ws = ThisWorkbook.Worksheets(1)
FilePath = "D:\certificate-of-earnings.pdf"
ws.Range("A1").Select
ws.OLEObjects.Add Filename:=FilePath, Link:=False, DisplayAsIcon:=True, Height:=15, Width:=51, IconLabel:="PDF"
End Sub

Related

Create excel attachment Object using VB or macros in a cell of Excel

Please advise how can I create a Object in a cell of Excel using macros.
Please refer below Image:
[
I want to attach attachment like in image but using Script or any kind of formulas.
Thanks
Here's a sample I created using the method described in my comment:
Excel macro
'Select the cell that should contain the object
Range("B5").Select
'Add an object to the given cell
ActiveSheet.OLEObjects.Add(Filename:= _
"C:\Users\de12668\Documents\Zeichnung1.vsd", Link:=False, DisplayAsIcon:= _
True, IconFileName:= _
"C:\WINDOWS\Installer\{90140000-0057-0000-0000-0000000FF1CE}\visicon.exe", _
IconIndex:=0, IconLabel:="A sample"). _
Select
Update 1
If the paths to the elements are provided in the first column, use this to add the appropriate links:
Dim myRange As range
Dim longLastRow As Long
Dim counter As Long
Set myRange = Worksheets(1).range("A1")
longLastRow = Cells(Rows.Count, myRange.Column).End(xlUp).Row
For counter = 1 To longLastRow
range("B" & counter).Select
ActiveSheet.OLEObjects.Add(Filename:= _
range("A" & counter).Value, Link:=False, DisplayAsIcon:= _
True, IconFileName:= _
range("A" & counter).Value, _
IconIndex:=0, IconLabel:=""). _
Select
Next
Open VBA editor (Alt+F11)
Tools->References-> Include "Microsoft Scripting Runtime"
Copy and paste the below code into excel VBA
Give the document path in A1
Run
Check the output whether it suits for you.
Sub CreateObject()
Dim shpGroup As Shape
Dim shpTextbox As Shape
Dim fso As New FileSystemObject
Dim mfile As File
Dim mfolder As Folder
Dim mpath As String
Dim mrow As Integer
mpath = ActiveSheet.Range("A1").Value 'Path of the document files in the local system
mrow = 2
If fso.FolderExists(mpath) Then
Set mfolder = fso.GetFolder(mpath)
For Each mfile In mfolder.Files
ActiveSheet.Hyperlinks.Add Anchor:=ActiveSheet.Range("A" & mrow), _
Address:=mfile.ShortPath, _
TextToDisplay:=mfile.ShortPath
ActiveSheet.Range("A" & mrow).Value = mfile.ShortPath
Set shpGroup = ActiveSheet.Shapes.AddPicture("C:\inetpub\wwwroot\learn\sun.jpg", msoFalse, msoTrue, 0, 0, 50, 50) 'give the Image path
shpGroup.LockAspectRatio = msoFalse
shpGroup.Left = ActiveSheet.Range("B" & mrow).Left
shpGroup.Top = ActiveSheet.Range("B" & mrow).Top
shpGroup.Width = ActiveSheet.Range("B" & mrow).Width
shpGroup.Height = ActiveSheet.Range("B" & mrow).Height
mrow = mrow + 1
Next
End If
Set mfile = Nothing
Set mfolder = Nothing
Set fso = Nothing
End Sub

Create new worksheet if does not exist, rename based on cell value, then reference that worksheet

I have 2 workbooks one has the vba (MainWb), the other is just a template (TempWb) that the code paste values and formulas from the mainworkbook. The TempWb only has one blank sheet named graphs. The code needs to open the xltx file (TempWb), add a sheet and rename based on value in a certain cell on the MainWb (if it does not already exist) and then to reference that new sheet in the copy values process from the MainWb. I tried recording a macro but it didn't really help. I have researched and put some stuff together but not sure if it fits and works. Any suggestions would be appreciated.
This is what I have so far.
Option Explicit
Sub ExportSave()
Dim Alpha As Workbook 'Template
Dim Omega As Worksheet 'Template
Dim wbMain As Workbook 'Main Export file
Dim FileTL As String 'Test location
Dim FilePath As String 'File save path
Dim FileProject As String 'Project information
Dim FileTimeDate As String 'Export Date and Time
Dim FileD As String 'Drawing Number
Dim FileCopyPath As String 'FileCopy save path
Dim FPATH As String 'File Search Path
Dim Extract As Workbook 'File Extract Data
Dim locs, loc 'Location Search
Dim intLast As Long 'EmptyCell Search
Dim intNext As Long 'EmptyCell Seach
Dim rngDest As Range 'Paste Value Range
Dim Shtname1 As String 'Part Platform
Dim Shtname2 As String 'Part Drawing Number
Dim Shtname3 As String 'Part Info
Dim rep As Long
With Range("H30000")
.Value = Format(Now, "mmm-dd-yy hh-mm-ss AM/PM")
End With
FilePath = "C:\Users\aholiday\Desktop\FRF_Data_Macro_Insert_Test"
FileCopyPath = "C:\Users\aholiday\Desktop\Backup"
FileTL = Sheets("Sheet1").Range("A1").Text
FileProject = Sheets("Sheet1").Range("E2").Text
FileTimeDate = Sheets("Sheet1").Range("H30000").Text
FileD = Sheets("Sheet1").Range("E3").Text
FPATH = "C:\Users\aholiday\Desktop\FRF_Data_Macro_Insert_Test\"
Shtname1 = wbMain.Sheets("Sheet1").Range("E2")
Shtname2 = wbMain.Sheets("Sheet1").Range("E3")
Shtname3 = wbMain.Sheets("Sheet1").Range("E4")
Select Case Range("A1").Value
Case "Single Test Location"
Case "Location 1"
Application.DisplayAlerts = False
Set wbMain = Workbooks("FRF Data Export Graphs.xlsm")
wbMain.Sheets("Sheet1").Copy
ActiveWorkbook.SaveAs Filename:=FileCopyPath & "\" & FileProject & Space(1) & FileD & Space(1) & FileTL & Space(1) & FileTimeDate & ".xlsx", FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close False
Set Alpha = Workbooks.Open("\\plymshare01\Public\Holiday\FRF Projects\Templates\FRF Data Graphs.xltx")
For rep = 1 To (Worksheets.Count)
If LCase(Sheets(rep)).Name = LCase(Shtname1 & Space(1) & Shtname2 & Space(1) & Shtname3) Then
MsgBox "This Sheet already exists"
Exit Sub
End If
Next
Sheets.Add after:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = Shtname1 & Space(1) & Shtname2 & Space(1) & Shtname3
Set Omega = Workbooks(ActiveWorkbook.Name).Sheets("ActiveWorksheet.Name")
locs = Array("FRF Data Export Graphs.xlsm")
'set the first data block destination
Set rngDest = Omega.Cells(3, 1).Resize(30000, 3)
For Each loc In locs
Set Extract = Workbooks.Open(Filename:=FPATH & loc, ReadOnly:=True)
rngDest.Value = Extract.Sheets("Sheet1").Range("A4:D25602").Value
Extract.Close False
Set rngDest = rngDest.Offset(0, 4) 'move over to the right 4 cols
Next loc
With ActiveWorksheet.Range("D3:D25603").Formula = "=SQRT((B3)^2+(C3)^2)"
ActiveWorkbook.Charts.Add
ActiveChart.ChartType = xlXYScatterLines
ActiveChart.SetSourceData Source:=Sheets("Graphs").Range("A3:D7"), PlotBy:=xlRows
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:=Shtname2
With ActiveChart
.HasTitle = True
.ChartTitle.Characters.Text = Shtname2
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Hz"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Blank"
End With
Application.ScreenUpdating = True
Case "Location 2"
Case "Location 3"
Case "Location 4"
Case Else
MsgBox "Export Failed!"
End Select
Application.DisplayAlerts = True
End Sub
Run-time error '91'
Object variable or With block not set
code lines
Shtname1 = wbMain.Sheets("Sheet1").Range("E2")
Shtname2 = wbMain.Sheets("Sheet1").Range("E3")
Shtname3 = wbMain.Sheets("Sheet1").Range("E4")
This is supposed to tell the code what to name the new created sheet
Fixed: Moved under
Set = wbMain = Workbooks("FRF Data Export Graphs.xlsm")
New Error:
Object doesnt support this property or method
code
If LCase(Sheets(rep)).Name = LCase(Shtname1 & Space(1) & Shtname2 & Space(1) & Shtname3) Then
A few things could be happening here
Shtname1 = wbMain.Sheets("Sheet1").Range("E2")
You are trying to access three objects and set a third. This means wbMain needs to be set and Sheets("Sheet1") need to be set and Range("E2") needs to exist.
You also, because you are setting Shtname1 as a string I'd be explicit about what value you want to go in there.
Shtname1 = wbMain.Sheets("Sheet1").Range("E2").Value
So with the breakpoint on that line and the locals window open (View > Locals Window) make sure everything is set. If it's not it needs to be. One of those values is not set.
If you do infact Set wbMain = Workbooks("FRF Data Export Graphs.xlsm") but it is in a different module or a different sub and wbMain is redeclared at the top of this sub these statements are in totally different contexts. The first wbMain is a different variable basically.

VBA to copy specific sheet to existing book

The task here is two fold (the first part already works though).
Task 1: Copy a sheet that's been selected from a combo box into a new document.
Task 2: Copy a specific sheet from the original document and add it to the new document that was created above.
So far I've got this: (but the second task doesn't work)
Sub Extract()
Dim wbkOriginal As Workbook
Set wbkOriginal = ActiveWorkbook
'sets site and engineer details into the estate page that is being extracted
Worksheets(FrontPage.CmbSheet.Value).Range("B3").Value = Worksheets("front page").Range("E6")
Worksheets(FrontPage.CmbSheet.Value).Range("D3").Value = Worksheets("front page").Range("N6")
Worksheets(FrontPage.CmbSheet.Value).Range("F3").Value = Worksheets("front page").Range("K6")
Worksheets(FrontPage.CmbSheet.Value).Range("B4").Value = Worksheets("front page").Range("F8")
Worksheets(FrontPage.CmbSheet.Value).Range("D4").Value = Worksheets("front page").Range("K8")
' copies sheet name from combo box into new document, saves it with site name and current date
' into C:\Temp\ folder for ease of access
With ActiveWorkbook.Sheets(FrontPage.CmbSheet.Value)
.Copy
ActiveWorkbook.SaveAs _
"C:\temp\" _
& .Cells(3, 2).Text _
& " " _
& Format(Now(), "DD-MM-YY") _
& ".xlsm", _
xlOpenXMLWorkbookMacroEnabled, , , , False
End With
Dim wbkExtracted As Workbook
Set wbkExtracted = ActiveWorkbook
Workbooks(wbkOriginal.Name).Sheets(DOCUMENTS).Copy _
After:=Workbooks(wbkExtracted.Name).Sheets(wbkExtracted.Name).Sheets.Count
'code to close the original workbook to prevent accidental changes etc
'Application.DisplayAlerts = False
'wbkOriginal.Close
'Application.DisplayAlerts = True
End Sub
I'm hoping one of you clever folks out there can tell me what I'm doing wrong :)
I think I know the problem you are running into. (Maybe) If you are working with a new instance of excel you need to save it then reopen it. It must have something to do with the object model. I had to do this not too long ago. Here is a snippet of the code I used.
Set appXL = New Excel.application
appXL.Workbooks.Add
Set wbThat = appXL.ActiveWorkbook
wbThat.application.DisplayAlerts = False
wbThat.SaveAs Filename:=strFilePath & "\" & strFileName
'This code needed to allow the copy function to work
wbThat.Close savechanges:=True
Set wbThat = Nothing
Set wbThat = application.Workbooks.Open(strFilePath & "\" & strFileName)
appXL.Quit
Set appXL = Nothing
'Copy Help page from this workbook to the report
wbThis.Sheets("Help").Copy after:=wbThat.Sheets(wbThat.Sheets.Count)
Sub Full_Extract()
Dim wbkOriginal As Workbook
Set wbkOriginal = ActiveWorkbook
'sets site and engineer details into the estate page that is being extracted
Worksheets(Sheet1.CmbSheet.Value).Range("B3").Value = Worksheets("front page").Range("E6")
Worksheets(Sheet1.CmbSheet.Value).Range("D3").Value = Worksheets("front page").Range("N6")
Worksheets(Sheet1.CmbSheet.Value).Range("F3").Value = Worksheets("front page").Range("K6")
Worksheets(Sheet1.CmbSheet.Value).Range("B4").Value = Worksheets("front page").Range("F8")
Worksheets(Sheet1.CmbSheet.Value).Range("D4").Value = Worksheets("front page").Range("K8")
' copies sheet name from combo box into new document, saves it with site name and current date
' into C:\Temp\ folder for ease of access
With ActiveWorkbook.Sheets(Array((Sheet1.CmbSheet.Value), "Z-MISC"))
.Copy
ActiveWorkbook.SaveAs _
"C:\temp\" _
& ActiveWorkbook.Sheets(Sheet1.CmbSheet.Value).Cells(3, 2).Text _
& " " _
& Format(Now(), "DD-MM-YY") _
& ".xlsm", _
xlOpenXMLWorkbookMacroEnabled, , , , False
End With
'code to close the original workbook to prevent accidental changes etc
Application.DisplayAlerts = False
wbkOriginal.Close
Application.DisplayAlerts = True
End Sub

How to loop through worksheets in a defined order using VBA

I have the below working code which loops through each worksheet and if the value defined in the range (myrange) is 'Y', it outputs those sheets into a single PDF document. My challange is that i want to define the order that they are output in the PDF based on the number value in the range (for example 1,2,3,4,5,6,7 etc) instead of 'Y'. I plan on using the same column in the myrange to check whether it needs to be output to PDF, by simply swapping the 'Y' for a number, such as '1' and '2'.
Currently the order is defined based on the location of the worksheet tabs. from left to right.
Any help will be much appreciated.
Sub Run_Me_To_Create_Save_PDF()
Dim saveAsName As String
Dim WhereTo As String
Dim sFileName As String
Dim ws As Worksheet
Dim printOrder As Variant '**added**
Dim myrange
On Error GoTo Errhandler
Sheets("Settings").Activate
' Retrieve value of 'Period Header' from Settings sheet
Range("C4").Activate
periodName = ActiveCell.Value
' Retrieve value of 'File Name' from Settings sheet
Range("C5").Activate
saveAsName = ActiveCell.Value
' Retrieve value of 'Publish PDF to Folder' from Settings sheet
Range("C6").Activate
WhereTo = ActiveCell.Value
Set myrange = Worksheets("Settings").Range("range_sheetProperties")
' Check if Stamp-field has any value at all and if not, add the current date.
If Stamp = "" Then Stamp = Date
' Assemble the filename
sFileName = WhereTo & saveAsName & " (" & Format(CDate(Date), "DD-MMM-YYYY") & ").pdf"
' Check whether worksheet should be output in PDF, if not hide the sheet
For Each ws In ActiveWorkbook.Worksheets
Sheets(ws.Name).Visible = True
printOrder = Application.VLookup(ws.Name, myrange, 4, False)
If Not IsError(printOrder) Then
If printOrder = "Y" Then
Sheets(ws.Name).Visible = True
End If
Else: Sheets(ws.Name).Visible = False
End If
Next
'Save the File as PDF
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
sFileName, Quality _
:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
' Unhide and open the Settings sheet before exiting
Sheets("Settings").Visible = True
Sheets("Settings").Activate
MsgBox "PDF document has been created and saved to : " & sFileName
Exit Sub
Errhandler:
' If an error occurs, unhide and open the Settings sheet then display an error message
Sheets("Settings").Visible = True
Sheets("Settings").Activate
MsgBox "An error has occurred. Please check that the PDF is not already open."
End Sub
---------------------- UPDATE: -------------------------------------
Thank you for all your input so far. I did get it to work briefly, but with more playing i've become stuck. I am now receiving a 'Subscript our of range' error with the below code at :
If sheetNameArray(x) <> Empty Then
Any ideas?
Sub Run_Me_To_Create_Save_PDF()
Dim saveAsName As String
Dim WhereTo As String
Dim sFileName As String
Dim ws As Worksheet
Dim myrange
ReDim sheetNameArray(0 To 5) As String
Dim NextWs As Worksheet
Dim PreviousWs As Worksheet
Dim x As Integer
'On Error GoTo Errhandler
Sheets("Settings").Activate
' Retrieve value of 'Period Header' from Settings sheet
Range("C4").Activate
periodName = ActiveCell.Value
' Retrieve value of 'File Name' from Settings sheet
Range("C5").Activate
saveAsName = ActiveCell.Value
' Retrieve value of 'Publish PDF to Folder' from Settings sheet
Range("C6").Activate
WhereTo = ActiveCell.Value
' Check if Stamp-field has any value at all and if not, add the current date.
If Stamp = "" Then Stamp = Date
' Assemble the filename
sFileName = WhereTo & saveAsName & " (" & Format(CDate(Date), "DD-MMM-YYYY") & ").pdf"
Set myrange = Worksheets("Settings").Range("range_sheetProperties")
For Each ws In ActiveWorkbook.Worksheets
printOrder = Application.VLookup(ws.Name, myrange, 4, False)
If Not IsError(printOrder) Then
printOrderNum = printOrder
If printOrderNum <> Empty Then
'Add sheet to array
num = printOrderNum - 1
sheetNameArray(num) = ws.Name
End If
End If
Next
MsgBox Join(sheetNameArray, ",")
'Order Tab sheets based on array
x = 1
Do While Count < 6
If sheetNameArray(x) <> Empty Then
Set PreviousWs = Sheets(sheetNameArray(x - 1))
Set NextWs = Sheets(sheetNameArray(x))
NextWs.Move after:=PreviousWs
x = x + 1
Else
Count = Count + 1
x = x + 1
End If
Loop
Sheets(sheetNameArray).Select
'Save the File as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=sFileName, Quality _
:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
' open the Settings sheet before exiting
Sheets("Settings").Activate
MsgBox "PDF document has been created and saved to : " & sFileName
Exit Sub
Errhandler:
' If an error occurs, unhide and open the Settings sheet then display an error message
Sheets("Settings").Visible = True
Sheets("Settings").Activate
MsgBox "An error has occurred. Please check that the PDF is not already open."
End Sub
You would want to define the worksheets in an array.
This example uses a static array, knowing the sheets order and what you want to print in advance. This does work.
ThisWorkbook.Sheets(Array("Sheet1","Sheet2","Sheet6","Master","Sales")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:=sFileName, Quality _
:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
The problem is that if a sheet is hidden, it will fail on the selection.
So you will need to already know which sheets pass the test to be printed or not before declaring the Array. Therefore you will need a dynamic array to build the list of Worksheets.
I did change how your PrintOrder works, instead of making the sheet invisible, it simply doesn't add it to the array, or vice versa, adds the ones you want to the array. Then you select the array at the end, and run your print macro that works.
I tested this using my own test values, and am trusting that your PrintOrder Test works. But this does work. I used it to print time sheets that only have more than 4 hours per day, and it succeeded, merging 5 sheets out of a workbook with 11 sheets into one PDF.. All of them qualified the test.
TESTED: Insert this instead of your For Each ws and add the Variable Declarations with yours
Sub DynamicSheetArray()
Dim wsArray() As String
Dim ws As Worksheet
Dim wsCount As Long
wsCount = 0
For Each ws In Worksheets
printOrder = Application.VLookup(ws.Name, myrange, 4, False)
If Not IsError(printOrder) Then
If printOrder = "Y" Then
wsCount = wsCount + 1
ReDim Preserve wsArray(1 To wsCount)
'Add sheet to array
wsArray(wsCount) = ws.Name
End If
End If
Next
Sheets(wsArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:=sFileName, Quality _
:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
edit: further explained context of my code to OP
Here is a bit of code I came up with. Basically you would want to take this and adapt it to fit your specific needs but the general idea should work!
Sub MovingPagesAccordingToNumberInRange()
Dim ws As Worksheet
Dim NextWs As Worksheet
Dim PreviousWs As Worksheet
Dim sheetNameArray(0 To 400) As String
Dim i As Integer
'This first loop is taking all of the sheets that have a number
' placed in the specified range (I used Cell A1 of each sheet)
' and it places the name of the worksheet into an array in the
' order that I want the sheets to appear. If I placed a 1 in the cell
' it will move the name to the 1st place in the array (location 0).
' and so on. It only places the name however when there is something
' in that range.
For Each ws In Worksheets
If ws.Cells(1, 1).Value <> Empty Then
num = ws.Cells(1, 1).Value - 1
sheetNameArray(num) = ws.Name
End If
Next
' This next section simply moves the sheets into their
' appropriate positions. It takes the name of the sheets in the
' previous spot in the array and moves the current spot behind that one.
' Since I didn't know how many sheets you would be using I just put
' A counter in the prevent an infinite loop. Basically if the loop encounters 200
' empty spots in the array, everything has probably been organized.
x = 1
Do While Count < 200
If sheetNameArray(x) <> Empty Then
Set PreviousWs = sheets(sheetNameArray(x - 1))
Set NextWs = sheets(sheetNameArray(x))
NextWs.Move after:=PreviousWs
x = x + 1
Else
Count = Count + 1
x = x + 1
End If
Loop
End Sub

Displaying only a determined range of data

I want to display to the user certain information that exists on a separated worksheet, whenever he clicks a button.
I can set Excel to "go" to this worksheet at the starting line of the range , but I could not find a way to hide everything else.
Is there some method for this, or do I have to hide all rows and columns?
Insert a UserForm in the Workbook's VB Project.
Add a ListBox control to the userform.
Then do something like this code in the UserForm_Activate event code:
Private Sub UserForm_Activate()
Dim tbl As Range
Set tbl = Range("B2:E7") '## Change this to capture the rang you need '
Me.Caption = "Displaying data from " & _
ActiveSheet.Name & "!" & tbl.Address
With ListBox1
.ColumnHeads = False
.ColumnCount = tbl.Columns.Count
.RowSource = tbl.Address
End With
End Sub
Which gives unformatted data from the range:
To export the range as an image, you could create an Image in the UserForm instead of a Listbox. Then this should be enough to get you started.
As you can see from this screenshot, the image might not always come out very clearly. Also, if you are working with a large range of cells, the image might not fit on your userform, etc. I will leave figuring that part out up to you :)
Private Sub UserForm_Activate()
Dim tbl As Range
Dim imgPath As String
Set tbl = Range("B2:E7") '## Change this to capture the rang you need '
imgPath = Export_Range_Images(tbl)
Caption = "Displaying data from " & _
ActiveSheet.Name & "!" & tbl.Address
With Image1
If Not imgPath = vbNullString Then
.Picture = LoadPicture(imgPath)
.PictureSizeMode = fmPictureSizeModeClip
.PictureAlignment = 2 'Center
.PictureTiling = False
.SpecialEffect = 2 'Sunken
End If
End With
End Sub
Function Export_Range_Images(rng As Range) As String
'## Modified by David Zemens with
' credit to: _
' http://vbadud.blogspot.com/2010/06/how-to-save-excel-range-as-image-using.html ##'
Dim ocht As Object
Dim srs As Series
rng.CopyPicture xlScreen, xlPicture
ActiveSheet.Paste
Set ocht = ActiveSheet.Shapes.AddChart
For Each srs In ocht.Chart.SeriesCollection
srs.Delete
Next
'## Modify this line as needed ##'
fname = "C:\users\david_zemens\desktop\picture.jpg"
On Error Resume Next
Kill fname
On Error GoTo 0
ocht.Width = rng.Width
ocht.Height = rng.Height
ocht.Chart.Paste
ocht.Chart.Export Filename:=fname, FilterName:="JPG"
Application.DisplayAlerts = False
ocht.Delete
Application.DisplayAlerts = True
Set ocht = Nothing
Export_Range_Images = fname
End Function
If you record a macro and hide some columns and rows manually, the code will be produced for you, and you will see how it's done.