MS Access VBA to format MS Excel export Problem

tranchemontaigne

Registered User.
Local time
Today, 04:51
Joined
Aug 12, 2008
Messages
203
BACKGROUND:
What I have already done is export data to MS Excel (via ADODB). What I want to do now is draw a box around the selected range. How do I do this.

GOAL:
Draw a border around the output range in the MS Excel export

SUMMARY OF EFFORT:
I can draw a border around each cell within the range, center align the values within each cell, and autofit the column width property with the following block of code

With WS.Range("A1:X49")
.Columns.AutoFit
.HorizontalAlignment = xlHAlignCenter
.Borders.Weight = xlMedium
End With


Unfortunately I don't want to outline every cell.


I want to outline a predefined range. If I was writing the code for execution within MS Excel VBA it would look like this. How do I adopt this block for execution within a MS Access VBA module?

Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone

With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With

With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With

With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With

With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With

Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone


Any help with syntax would be appreciated.
________
Granada (Europe)
 
Last edited:
I see your problem this way:

As far as I know Access does only transfer Data from its dB to Excels dB, not Command strings. What you want to do is execute Excel instructions within Excel domain. So only if Access could transfer Excel instructions into the Excel Macro Set you would have a chance to accomplish this job.

If you just want to mark the Excel data so that it easily can be identified, may be you could think on something used in the early days of dBase displays: o box drawn with ASCII characters: sending as the first and last line a series of “-“characters and add a first and last column with a “|” character. Not a very elegant solution for today, but depending on what you need!?

Another thing to try could be to include the boundaries of your box within the transferred data, as the first line for example - the info of how much columns and lines you a sending is available within Access. Your Excel macro can read these parameters and draw the box accordingly. Disadvantage is that you have to start the macro manually (and send the parameter data always to predetermined fields).
 
Actually, you CAN use vba in Access to programmatically mess about with Excel's worksheet functions/formatting tools etc. The key to it is to use the MSExcel reference in vba, and you need to open an excel workbook object etc, first. There are example threads you can find on the web that demonstrate this general approach.

I don't know any examples specific to drawing tools though, sorry.

Edit: Here's a function I wrote/modified that takes an excel file created by exporting a query, and then creates and formats a chart based on the data in the spreadsheet. Obviously, it won't work without the correct data in the right places, but it shows the general approach to manipulating the spreadsheet from within Access vba (after much searching and fiddling on the topic).


Code:
Function CreateChart(strFileName As String, intRows As Integer, Bacteria As Integer)

   Dim xlApp As Excel.Application
   Dim xlWrkbk As Excel.Workbook
   Dim xlWrkSh As Excel.Worksheet
   Dim xlChartObj As Excel.Chart
   Dim xlSourceRange As Excel.Range
   Dim myRange As String
   Dim firstlineflag As Boolean
   Dim secondlineflag As Boolean
   Dim blankcount As Integer
   Dim BlankRange As String
   Dim xlBlankTotal As Excel.Range
   'Dim xlColPoint As Excel.Point

   On Error GoTo Err_CreateChart
   
    Select Case Bacteria
    Case 7 'Enterococcus
        myRange = "A1:A" & (intRows + 1) & ",G1:K" & (intRows + 1)
    Case 8 'Fecal Coliforms
        myRange = "A1:F" & (intRows + 1)
    Case 49 'E. coli
        myRange = "A1:A" & (intRows + 1) & ",L1:P" & (intRows + 1)
    End Select
    
   ' Create an Excel workbook file based on the
   ' object specified in the second argument.

   ' Create a Microsoft Excel object.
   Set xlApp = CreateObject("Excel.Application")
   ' Open the spreadsheet to which you exported the data.
   Set xlWrkbk = xlApp.Workbooks.Open(strFileName)
   ' Determine the size of the range and store it.
   
   
   
   Set xlSourceRange = _
         xlWrkbk.Worksheets("tmptbl_BacteriaStats").Range(myRange)
         
        'make sure there is data for the first and second line or else you will get an error
        Select Case Bacteria
        Case 7 'Enterococcus

        
        If DCount("[Sitenumber]", "tmptbl_BacteriaStats", "[Enterococcus - Mean - Geometric (Upper Limit)] & '' <> ''") = 0 Then firstlineflag = True
        If DCount("[Sitenumber]", "tmptbl_BacteriaStats", "[Enterococcus - Maximum - Daily (Upper Limit)] & '' <> ''") = 0 Then secondlineflag = True

        Case 8 'fecals

        If DCount("[Sitenumber]", "tmptbl_BacteriaStats", "[Fecal Coliform - Mean - Geometric (Upper Limit)] & '' <> ''") = 0 Then firstlineflag = True
        If DCount("[Sitenumber]", "tmptbl_BacteriaStats", "[Fecal Coliform - Percentile - 90th (Upper Limit)] & '' <> ''") = 0 Then secondlineflag = True
        
        Case 49 'E coli
        firstlineflag = True
        secondlineflag = True
        End Select
         
   ' Create a new chart.
   Set xlChartObj = xlApp.Charts.Add
   ' Format the chart.
   With xlChartObj


        ' Set the range of the chart.
        .SetSourceData source:=xlSourceRange, PlotBy:=xlColumns
        .ApplyCustomType ChartType:=xlBuiltIn, TypeName:="Line - Column"
        
        ' Specify that the chart is located on a new sheet.
   
        Select Case Bacteria
        Case 7 'Enterococcus
            .Location WHERE:=xlLocationAsNewSheet, Name:="Enterococcus Results"
        Case 8 'Fecal Coliforms
            .Location WHERE:=xlLocationAsNewSheet, Name:="Fecal Results"
        Case 49 'E. coli
            .Location WHERE:=xlLocationAsNewSheet, Name:="E coli Results"
        End Select

        
        ' Create and set the title; set title font.
        .HasTitle = True
        With .ChartTitle
        
            Select Case Bacteria
            Case 7 'Enterococcus
                .Characters.Text = "Enterococcus Results vs Standards"
            Case 8 'Fecal Coliforms
                .Characters.Text = "Fecal Coliform Results vs Standards"
            Case 49 'E. coli
                .Characters.Text = "E. coli Results vs Standards"
            Case Else
                .Characters.Text = "Edit title Here"
            End Select

           .Font.Size = 18
        End With
        
        .PlotArea.ClearFormats
      


        ' Use the legend.
        .HasLegend = True
        With .Legend
          .position = xlBottom
          .LegendEntries(1).Delete
          If firstlineflag = True Then
            .LegendEntries(3).Delete
            If secondlineflag = True Then .LegendEntries(3).Delete
          Else
            If secondlineflag = True Then .LegendEntries(4).Delete
          End If
        End With
      
        'setup X-Axis
        With .Axes(xlCategory, xlPrimary)
          .HasTitle = False
          .TickLabels.Orientation = 0
          '.Border.LineStyle = xlAutomatic
          .MajorTickMark = xlOutside
          .MinorTickMark = xlNone
        End With
      
        .Axes(xlCategory, xlSecondary).HasTitle = False
        .Axes(xlValue, xlSecondary).HasTitle = False
        
        'Setup y-Axis
        With .Axes(xlValue, xlPrimary)
          .HasTitle = True
          .MinimumScaleIsAuto = True
          .MaximumScaleIsAuto = True
          .MinorUnitIsAuto = True
          .MajorUnitIsAuto = True
          .Crosses = xlAutomatic
          .ReversePlotOrder = False
          .ScaleType = xlLogarithmic
          .DisplayUnit = xlNone
          .AxisTitle.Characters.Text = "CFU/100mL"
          '.Weight = xlHairline
          '.LineStyle = xlAutomatic
          .MajorTickMark = xlOutside
          .MinorTickMark = xlNone
          .TickLabelPosition = xlNextToAxis
        End With


        'hide the bars for the sample count series
        With .SeriesCollection(1)
          .Border.Weight = xlThin
          .Border.LineStyle = xlNone
          .Shadow = False
          .InvertIfNegative = False
          .Interior.ColorIndex = xlNone
          .ApplyDataLabels Type:=xlDataLabelsShowValue, AutoText:=True, LegendKey:=False
        End With
        'format the sample count data labels
        With .SeriesCollection(1).DataLabels
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlCenter
            .position = xlLabelPositionInsideBase
            .Orientation = xlHorizontal
        End With

        With .SeriesCollection(2)
        .Border.Weight = xlThin
        .Border.LineStyle = xlAutomatic
        .Shadow = False
        .InvertIfNegative = False
        .Interior.ColorIndex = 5
        .Interior.Pattern = xlSolid
        End With

        With .SeriesCollection(3)
        .Border.Weight = xlThin
        .Border.LineStyle = xlAutomatic
        .Shadow = False
        .InvertIfNegative = False
        .Interior.ColorIndex = 38
        .Interior.Pattern = xlSolid
        End With

        
        'make sure there is data for the first line or else you will get an error
        If firstlineflag = False Then
            With .SeriesCollection(4)
            .Border.Weight = xlMedium
            .Border.ColorIndex = 5
            .Border.LineStyle = xlContinuous
            .MarkerBackgroundColorIndex = xlAutomatic
            .MarkerForegroundColorIndex = xlAutomatic
            .MarkerStyle = xlNone
            .Smooth = False
            .MarkerSize = 5
            .Shadow = False
            End With
        End If
        
        'make sure there is data for the second line or else you will get an error
       
        If secondlineflag = False Then
            With .SeriesCollection(5)
            .Border.Weight = xlMedium
            .Border.ColorIndex = 3
            .Border.LineStyle = xlContinuous
            .MarkerBackgroundColorIndex = xlNone
            .MarkerForegroundColorIndex = xlAutomatic
            .MarkerStyle = xlNone
            .Smooth = False
            .MarkerSize = 5
            .Shadow = False
            End With
        End If

        
   End With

    xlApp.ActiveWindow.Zoom = 100

   ' Save and close the workbook
   ' and quit Microsoft Excel.
   With xlWrkbk

      .Save
      .Close
   End With

   xlApp.Quit

Exit_CreateChart:
   Set xlSourceRange = Nothing
   'Set xlColPoint = Nothing
   Set xlChartObj = Nothing
   Set xlWrkbk = Nothing
   Set xlApp = Nothing
   Exit Function

Err_CreateChart:

   MsgBox CStr(Err) & " " & Err.Description
   Resume Exit_CreateChart

End Function

And no, I'm NOT an expert on this topic. But it does work to do what I wanted it to do :)
 
Last edited:
You are right CraigDolphin, when I looked at your code I remembered that I saw some of this astonishing stuff before, in “the Access Web” site I think, (eg http://www.mvps.org/access/modules/mdl0006.htm) but I completely forgot about it (I hope its because it looked rather weird to me and not because Alzheimer is already on its way) - sorry for the misleading.
 
No problem....I agree with you. This exercise does veer into the arcane, somewhat. But it is nice to know it can be done. :)

I tend to record a macro in excel to figure out what the specific vba for manipulating the chart/spreadsheet should be, then copy and paste that into the Access module, and tweak til it works. :) I'm not half as clever as some of the folks around here when it comes to this stuff :)
 

Users who are viewing this thread

Back
Top Bottom