Excel VBA date bug

This error was found in Excel 2010 32 bit but may be present in other versions. The error happens when writing specific dates to an Excel cell. The VBA code
Dim datDate as Date
datDate = CVDate(41586.9999999995)
ActiveWorkbook.Sheets("Sheet1").Cells(3, 2).Value=datDate
ActiveWorkbook.Sheets("Sheet1").Cells(3, 2).Value=CDbl(41586.9999999995)
Will result in the following output to the Excel sheet
11/8/2013 0:00
11/9/2013 0:00
Both dates should be 11/9/2013. The error happens when writing a date to an Excel cell when the is almost (less than a second) before midnight. The conversion of the variable from date to double precision type fixes the bug.

Allan wrote:
Dim datDate as Date
datDate = CVDate(41586.9999999995)
ActiveWorkbook.Sheets("Sheet1").Cells(3, 2).Value=datDate
ActiveWorkbook.Sheets("Sheet1").Cells(3, 2).Value=CDbl(41586.9999999995)
Will result in the following output to the Excel sheet
11/8/2013 0:00
11/9/2013 0:00
Both dates should be 11/9/2013.
Yes, this is a defect in the range.Value property.
You can work around it by using the range.Value2 property.  Or by not using type Date at all.
(Aha!  I stumbled upon another alternative.  See comments below about creating a column of date/times.)
I always use type Double instead of type Date because VBA sometimes does "strange" things with type Date expressions.
In the rare circumstances where VBA requires type Date, I use CDate(doubleVariable).  That does not change the internal representation of doubleVariable.
The following might help to understand the problem. [1]
Sub doit()
    Dim d As Date
    Columns("a:c").Clear
    d = Evaluate("value(""11/08/2013 23:59:59.499"")")
    Range("a1").Value = d
    Range("b1").Value2 = d
    Range("c1").Formula = "=b1"
    d = Evaluate("value(""11/08/2013 23:59:59.500"")")
    Range("a2").Value = d
    Range("b2").Value2 = d
    Range("c2").Formula = "=b2"
    Range("a1:b2").NumberFormat = "mm/dd/yyyy hh:mm:ss.000"
    Range("c1:c2").NumberFormat = "mm/dd/yyyy hh:mm"
    Columns("a:c").AutoFit
End Sub
The results are:
A1: 11/08/2013 23:59:59.000
B1: 11/08/2013 23:59:59.499
C1: 11/08/2013 23:59
A2: 11/08/2013 00:00:00.000
B2: 11/08/2013 23:59:59.500
C2: 11/09/2013 00:00
Note that C2 is correct.  So the problem is in VBA, not Excel. [2]
When VBA assigns an expression of type Date to range.Value, it rounds to the second.  (For no good reason, IMHO.)
However, VBA makes a rookie error in the rounding:  it rounds time separately, failing to add any integer carry-over to the date.
As demonstrated in C2, when formatting time as h, h:mm or h:mm:ss, Excel does round to the second.  But it does it correctly.
Allan wrote:
The value 41586.9999 is just 0.1 second short of midnight. If Excel truncated the last second instead of rounding the the date in the Excel cell should be 11/8/2013 23:59:59
I think rounding to the second (or fraction of a second indicated by the format) is the correct thing to do.
If Excel (and VBA) truncated to the second, we might have the following undesirable situation.
A1:  =VALUE("11/08/2013 23:59:59")
formatted as mm/dd/yyyy hh:mm:ss displays 11/08/2013 23:59:59
B1:  =MOD(A1,1)
formatted as hh:mm:ss displays 23:59:58 (!)
because the representation of 23:59:59 in A1 is infinitesimally smaller than the time constant 23:59:59. [3]
Allan wrote:
The error is that when using VBA code to create a column of dates by hour you sometimes get an incorrect result in the Excel cell. I fixed this issue by adding 0.1 second to the date before writing to the Excel cell.
Adding 0.1 might be adequate for your situation.  But in general, it works only by coincidence.
Allan wrote:
There are other ways to work around this bug but I think that this is the most efficient.
That depends on how you implemented the loop, which you did not share.  Based on your previous example, I assume your "efficient" implementation is something like the following:
Dim datDate as Date
datDate = 41586
For i = 1 To n
datDate = DateAdd("h", 1, datDate)
ActiveWorkbook.Sheets("Sheet1").Cells(20 + i, 2).Value = datDate + 0.1/86400
Next i
The following is probably many times faster, although you might not notice if n is very small.
Dim d0 As Date, d As Date, v(1 To n, 1 To 1) As Date
d0 = #11/8/2013#
For i = 1 To n
    ' multiply to minimize "arithmetic drift": cumulative floating-point anomalies
    d = d0 + i * TimeSerial(1, 0, 0)
    ' round to the second
    v(i, 1) = Int(d * 86400 + 0.5) / 86400
Next
ActiveWorkbook.Sheets("Sheet1").Cells(21, 2).Resize(n, 1).Value = v
Actually, the explicit rounding is probably redundant, considering the 1-hour increment.  It is probably sufficient for the loop to be:
For i = 1 To n
    ' multiply to minimize "arithmetic drift": cumulative floating-point anomalies
    v(i,1) = d0 + i * TimeSerial(1, 0, 0)
Next
As noted above, in general, it would be better to use range.Value2 instead of range.Value.
I use range.Value here to make an "aha!" point:  when "v" is an array, range.Value does not round or otherwise alter the assigned values.
[EDIT] Also, I use type Date here to minimize differences and focus on "teaching" points.  Normally, I use type Double.  No reason not to.
[1] I use Evaluate("value(""11/08/2013 23:59:59.500"")") instead of #11/08/2013 23:59:59# + 0.5/86400 because the latter is infinitesimally
less than 11/08/2013 23:59:59.500, due to floating-point arithmetic anomalies.  So it does not demonstrate the problem because VBA correctly
rounds down to 11/08/2013 23:59:59.
[2] Arguably, the problem could be in Excel's handling of the data passed from VBA, set up by the range.Value property.  But that seems unlikely since I cannot think of any reason why Excel would round to the second.  Normally, it does not unless
the cell format requires it. [EDIT] Even then, Excel rounds only for display purposes; it does not round the underlying actual value (unless the "Precision as displayed" option is set).
[3] Arguably, we should write --TEXT(MOD(A1,1),"hh:mm:ss") instead of simply MOD(A1,1), because MOD(A1,1) is not the same internal representation.  But the point remains the same:  if Excel (and VBA) truncated to the second, that would
result in 23:59:58 instead of 23:59:59 as expected.

Similar Messages

  • How to get Data from SAP B1 through Journal Entries objects (Excel VBA)

    Hi Genius
    i had try to login SAB B1 thorugh MS Excel VBA code and it worked well. but i need some questions regards getting the data from after login. that means i want the Posting date, Transaction No, account code, debit and credit amount from Journal entries posted in a particular day through MS excel VBA into excel sheets 1 cell A1:E1
    how i get it if any possible ways to do that
    here my code to login
    Public Sub login()
        Sheets("Login").Select  'access the login tab
        Worksheets("Login").Range("B1").Activate 'put focus on cell B1 (manager)
        B1UserID = Trim(ActiveCell.Value2) 'set Businsss One user
        ActiveCell.Offset(1, 0).Activate
        B1Password = Trim(ActiveCell.Value2) 'set Business One password
        ActiveCell.Offset(1, 0).Activate
        sqluser = Trim(ActiveCell.Value2) 'set SQL user
        ActiveCell.Offset(1, 0).Activate
        sqlpass = Trim(ActiveCell.Value2) 'set SQL password
        ActiveCell.Offset(1, 0).Activate
        Db = Trim(ActiveCell.Value2)      'set Database name
        ActiveCell.Offset(1, 0).Activate
        Server = Trim(ActiveCell.Value2)  'set Server name
        Set company1 = New SAPbobsCOM.Company  'initialate DI company object
        company1.DbServerType = dst_MSSQL2005
        company1.Server = Server
        company1.DbUserName = sqluser
        company1.DbPassword = sqlpass
        company1.CompanyDB = Db
        company1.UserName = B1UserID
        company1.Password = B1Password
        'connect to the database
         lRetCode = company1.Connect
            If lRetCode <> 0 Then
                sErrMsg = company1.GetLastErrorDescription
                MsgBox (sErrMsg)
            Else
                MsgBox ("Connected to: " & company1.CompanyName)
            End If
    End Sub
    pls help me
    advance thanks to solvers

    Gordons way is the easiest - just query the OJDT table for journal entry headers and JDT1 for journal entry lines if needed.
    But if you want to work with the business objects:
    'Journal entry
       Dim oJE As SAPbobsCOM.JournalEntries
       Set oJE = company1.GetBusinessObject(oJournalEntries)
       oJE.GetByKey(1234)
       Dim postingDate as String
       postingDate = oJE.DueDate
    'etc etc

  • CALL RFC DATA FROM TWO LINKED TABLES IN EXCEL VBA

    Hi,
    I am using Excel VBA to call information from tables in SAP.
    This is working correctly, however I now need to be able to call information from another table where the two tables are linked by a common data field.
    Example.
    The first table I have lists all items in stock and contains an article number. The second table contains all article numbers and their descriptions.
    I want to be able to call the first table but to have the article codes description on there aswell.
    Here is the code I am currently using.
    Sub GetTable()
    'Connect to SAP
    Dim sapConn As Object 'Declare variant
    Set sapConn = CreateObject("SAP.Functions") 'Create ActiveX object
    sapConn.Connection.System = "QA2"
    sapConn.Connection.client = "900"
    sapConn.Connection.user = "mbrough"
    sapConn.Connection.Password = "st34lh"
    sapConn.Connection.Language = "EN"
    If sapConn.Connection.Logon(1, False) <> True Then 'Try Logon
       MsgBox "Cannot Log on to SAP"
    End If
    'Define the table specifics
    Dim objRfcFunc As Object
    Set objRfcFunc = sapConn.Add("RFC_READ_TABLE")
    Dim objQueryTab, objRowCount As Object
    Set objQueryTab = objRfcFunc.Exports("QUERY_TABLE")
    objQueryTab.Value = "LQUA"
    Set objRowCount = objRfcFunc.Exports("ROWCOUNT")
    objRowCount.Value = "15000"
    Dim objOptTab, objFldTab, objDatTab As Object
    Set objOptTab = objRfcFunc.Tables("OPTIONS")
    Set objFldTab = objRfcFunc.Tables("FIELDS")
    Set objDatTab = objRfcFunc.Tables("DATA")
    'Set the condition and refresh the table
    objOptTab.FreeTable
    objOptTab.Rows.Add
    objOptTab(objOptTab.RowCount, "TEXT") = "LGTYP BETWEEN 'K01' AND 'K06'"
    'Set fields to obtain and refresh table
    objFldTab.FreeTable
    'Then set values to call
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "LGNUM"
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "MATNR"
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "WERKS"
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "LGTYP"
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "LGPLA"
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "GESME"
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "VERME"
    objFldTab.Rows.Add
    objFldTab(objFldTab.RowCount, "FIELDNAME") = "MEINS"
    If objRfcFunc.Call = False Then
       MsgBox objRfcFunc.Exception
    End If
    Dim objDatRec As Object
    Dim objFldRec As Object
    For Each objDatRec In objDatTab.Rows
       For Each objFldRec In objFldTab.Rows
          Cells(objDatRec.Index, objFldRec.Index) = _
                Mid(objDatRec("WA"), objFldRec("OFFSET") + 1, objFldRec("LENGTH"))
       Next
    Next
    End Sub
    The table which contains the article descriptions is called 'MAKT' and this table also contains the column 'MATNR' which is the article field.
    Many thanks,
    Mike

    Is there no way of connecting the tables within the code.
    IT won't give me access to SE11
    Thanks,
    Mike

  • Date parameter has error in Excel VBA

    Hi Expert,
      I follow up experts code to create a query in Excel VBA, but when running, I got error(Invalid column name "StartDate") in SQL query. I don't know how to fix it because beginner. I hope somebody can help.
    The code is this.
    Public Sub Run()
        Dim SQL As String
        Dim Connected As Boolean
        Dim StartDate As Date
        Dim curdate As Date
        Dim MsgDate As String
        Dim TitleMsg As String
        MsgDate = "Enter the Start Date in A2 to use for these Timesheets (d/mm/yy), or Accept the Default (Today - 30)"
        TitleMsg = "Timesheet Start Date"
        curdate = Date - 30
        MsgBox (MsgDate)
        StartDate = Application.InputBox(MsgDate, TitleMsg, FormatDateTime(curdate, vbShortDate), Type:=1)
        ' Our query
        SQL = "select [Posting Date],[Ship-to Code],[External Document No_],[Order No_],[Pallet Amount]" & _
                "from dbo.[Valley Fine Foods$Sales Shipment Header]" & _
                "where [Location Code] = 'BE' and [Pallet Vendor] = 'PECO' and [Posting Date] >= ""'StartDate'"";"
        ' Connect to the database
        Connected = Connect("vffserver9m", "vffnav2013")
        If Connected Then
            ' If connected run query and disconnect
            Call Query(SQL)
            Call Disconnect
        Else
            ' Couldn't connect
            MsgBox "Could Not Connect!"
        End If
    End Sub
    James Liang

    Try
    SQL = "SELECT [Posting Date], [Ship-to Code], [External Document No_], [Order No_], [Pallet Amount] " & _
    "FROM dbo.[Valley Fine Foods$Sales Shipment Header] " & _
    "WHERE [Location Code] = 'BE' and [Pallet Vendor] = 'PECO' and [Posting Date] >= #" & _
    Format(StartDate, "yyyy-mm-dd") & "#"
    or
    SQL = "SELECT [Posting Date], [Ship-to Code], [External Document No_], [Order No_], [Pallet Amount] " & _
    "FROM dbo.[Valley Fine Foods$Sales Shipment Header] " & _
    "WHERE [Location Code] = 'BE' and [Pallet Vendor] = 'PECO' and [Posting Date] >= '" & _
    Format(StartDate, "yyyy-mm-dd") & "'"
    Regards, Hans Vogelaar (http://www.eileenslounge.com)

  • Excel VBA to access sharepoint list without permission

    Hi,
    I do find solution to retrieve the SharePoint list from excel VBA but my problem now is on the SharePoint permission to the list.
    I am developing this solution in excel because i don't want the particular user to access the list direct from the portal because the list contains some unique and confidential data. So what i did was created a new view in the portal with selected column
    and i connect to the view from excel. So every time the user want to retrieve the data, he can run macro to refresh the data in the excel.
    When i run the macro it can generate the list because i do have permission but if i run the same macro on the person machine, excel request for username and password because he don't have the permission to the list.
    Are there any work around to allow the user to generate the data in excel without permission to the SharePoint list.
    Thanks for the help.

    I've done this before using SQL Server Reporting Services integrated into SharePoint.
    Using SSRS, create the report you want the end user to view. Then create a Report Subscription, emailing the end user (or putting it in a file share/Doc Lib) the report. If they want to run it interactively, you can enable caching on the report, which would
    pull the report from the last time it was scheduled to run (the data would not be 'real time' in this case).
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • Excel VBA + SAP Scripting / How can I send an instruction to a background window without bringing it up?

    Hello guys,
    I need to send keys to a window in the background, but I don't want it to pop up when I do it as it may cause some errors if I'm typing something at that moment. Is this possible?
    The script I'm working on converts a spool to a pdf, but when the save as window comes up, the script stops recording because that is not a SAP screen, but a windows screen.
    I was actually able to make it work by ending the script right before executing the transaction, then I used AppActivate and SendKeys to execute the transaction by pressing F8 and saving the file by pressing enter, but I still have these windows popping up while the macro is running, so, is it possible to have the SendKeys point to a specific application without it bringing it to the foreground?
    Also, please note that I am new to programming, so I'm not familiar with all the functions.
    Thanks in advance.

    Hello Jahir.
    I had several similar request in past.
    One requirement was mass convertion of PM orders printout from spool to PDF.
    I found a solution where a small ABAP-Report (implemented in coding-area of an SQ02 infoset) Transfer spool data from my SAP user as PDF to a temp Folder on my local HDD.
    Then I convert this PDF-files with an small application (pdf2txt.exe) to text-files. Where a small Excel VBA code got an specific text as identifier (PM order number).
    So I have pdf-files with spoolnumber-naming and dedicated PM order number. So a small VBA code is renaming my files for better identification by enduser.
    Another method was to write an small VBA macro which is able to identify Save-As dialogbox and fillin a specific filename and press 'Save' by using ESER32-API methods and functions.
    As you are new with programming I guess both methods are a Little bit to complex for you.
    LEt me know when you Need more Information for one of above used methods by me.
    MAy you can give some more Details in which Transaction you will Trigger the spools.
    Br, Holger

  • Using Excel VBA to Print to PDF File?

    Hi, All !!
    I have an Excel VBA application that creates Excel reports.  These need to be sent external to our company in PDF format.  I've downloaded the Acrobat SDK and have found the VB sample for AdobePDFSilent.  Unfortunately, it appears that this is written for VB or VB.Net as I don't have any of the data types available that are created in the code.  However, from another forum, I've gotten some VB code that appears to do many of the processes included in the SDK sample.
    The code below doesn't give me any errors, but no PDF file is created.
    My VBA code
    Declare Function RegOpenKeyA Lib "advapi32.dll" ( _
        ByVal Key As Long, _
        ByVal SubKey As String, _
        NewKey As Long) As Long
    Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" ( _
        ByVal hKey As Long, _
        ByVal lpValueName As String, _
        ByVal Reserved As Long, _
        ByVal dwType As Long, _
        lpData As Any, _
        ByVal cbData As Long) As Long
    Declare Function RegCloseKey Lib "advapi32.dll" ( _
        ByVal hKey As Long) As Long
    Sub TestPrintPDF()
        Dim strDefaultPrinter As String
        Dim strOutFile As String
        Dim lngRegResult As Long
        Dim lngResult As Long
        Dim dhcHKeyCurrentUser As Long
        Dim PDFPath As String
        Const dhcRegSz As Long = 1
    1    Workbooks.Open ("\\master\fnshares\bcbcm\Client Management\Client Services\New Account Fees\09 September 2010\3Q10 Rebate Ltrs\Infi\MacroTest\A02.xls")
    2    Select Case ActiveWorkbook.Sheets.Count
    3        Case 1
    4            Sheets(1).Select
    5        Case 2
    6            Sheets(Array(Sheets(1).Name, Sheets(2).Name)).Select
    7        Case 3
    8            Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name)).Select
    9        Case 4
    10            Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name, Sheets(4).Name)).Select
    11        Case 5
    12           Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name, Sheets(4).Name, Sheets(5).Name)).Select
    13      Case 6
    14         Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name, Sheets(4).Name, Sheets(5).Name, Sheets(6).Name)).Select
    15  End Select
    16  dhcHKeyCurrentUser = &H80000001
    17  strDefaultPrinter = Application.ActivePrinter
    18  PDFPath = ActiveWorkbook.Path & Application.PathSeparator 'The directory in which you want to save the file
    19  strOutFile = PDFPath & Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & ".pdf" 'Change the pdf file name if required. This should have the fully qualified path
    20  lngRegResult = RegOpenKeyA(dhcHKeyCurrentUser, "Software\Adobe\Acrobat Distiller\PrinterJobControl", lngResult)
    21  lngRegResult = RegSetValueEx(lngResult, Application.Path & "\Excel.exe", 0&, dhcRegSz, ByVal strOutFile, Len(strOutFile))
    22  lngRegResult = RegCloseKey(lngResult)
    23  ThisWorkbook.ActiveSheet.PrintOut copies:=1, ActivePrinter:="Adobe PDF"
    24  Application.ActivePrinter = strDefaultPrinter
    25  ActiveWorkbook.Close False
    End Sub
    From what I can determine, the lines 17 & 24 combined basically accomplish the same thing as the SaveandUpdateDefaultPrinter function in the SDK (get and save the current default printer and return it to that default after printing the PDF).
    Line 20 opens the Registry key for Distiller\PrinterJobControl which is done in part of the ConvertFile function in the following SDK code.
    SDK Code
                Dim objDistillerRegKey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
                Dim strDistillerSubKey As String = "SOFTWARE\\Adobe\\Acrobat Distiller\\PrinterJobControl"
                'Open Current User's Distiller Subkey for writing
                objDistillerRegKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(strDistillerSubKey, True)
    Line 21 sets the Registry key for Excel with the name of the PDF file to output which also appears to be done in part of the ConvertFile function in the following code.
    SDK Code
               If (Not objDistillerRegKey Is Nothing) Then     'set reg key value for this app and file
                    objDistillerRegKey.SetValue(strAppPath, strOutputFile)
                    objDistillerRegKey.Close()
                End If
    I have verified, using RegEdit, that this Registry key does get set with the desired output filename.
    Line 23 prints the Excel file to PDF when done manually (this was recorded using the Excel Macro Recorder).  This should be comparable to the PrintToAdobePDF function in the SDK as below.
    SDK Code
        Private Sub PrintToAdobePDF(ByVal InputfilePath As String)
            'Prints InputFilePath to the AdobePDF printer.
            'Since we just gathered all this info programmatically,
            'this function assumes the file is present, that it has an
            'associated application and that the current user has print privileges.
            'Define properties for the print process
            Dim pProcInfo As New ProcessStartInfo
            pProcInfo.FileName = InputfilePath
            pProcInfo.Verb = "Print"
            'Make process invisible
            pProcInfo.CreateNoWindow = True
            pProcInfo.WindowStyle = ProcessWindowStyle.Hidden
            'start print process
            Dim pMyProc As Process = Process.Start(pProcInfo)
            pMyProc.WaitForExit()
        End Sub
    These are some of the statements I can't do because I don't have a ProcessStartInfo type.  What am I doing wrong or NOT doing that the PDF file is not created?  I hope I've described my situation in enough, but not too much detail.  Thanks for your help.
    Nate Brei

    Reinhard & Karl Heinz,
    Thank you both for your responses and willingness to work with me on this problem.  This is driving me crazy & is getting very frustrating.  It seems that I've tried everything that people have suggested (I've also posted on a VB Forum that I subscribe to) and I'm basically doing what works for everyone else but doesn't work for me.  I've got to be close.
    Reinhard, regarding your last post, it doesn't appear to be a one-time setting.  Everytime I come into the Printers Property box (even after I've printed a PDF document manually, that option about system & document fonts is ALWAYS turned on.  If it is a registry setting, please let me know how to turn it off.  I'm using Adobe Acrobat 9 Standard.
    Karl Heinz, I've tried that based on my initial post (see the code there).  Since your post, I tried it again.  I get the same result, NO FILE is produced anywhere.
    I wish I could post pictures, but evidently I can't.  So, I going to post first my code (in case you want to try to recreate my problem), then the values of the variables in that code when I run it (so you can I have everything set correctly as far as I know), and finally, the values of the Registry entries that I have after I run it.  So, please bear with me as the post may be a little long.
    My Code
    Declare Function RegOpenKeyA Lib "advapi32.dll" ( _
        ByVal Key As Long, _
        ByVal SubKey As String, _
        NewKey As Long) As Long
    Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" ( _
        ByVal hKey As Long, _
        ByVal lpValueName As String, _
        ByVal Reserved As Long, _
        ByVal dwType As Long, _
        lpData As Any, _
        ByVal cbData As Long) As Long
    Declare Function RegCloseKey Lib "advapi32.dll" ( _
        ByVal hKey As Long) As Long
    Sub TestPrintPDF()
        Dim strDefaultPrinter As String
        Dim strOutFile As String
        Dim lngRegResult As Long
        Dim lngResult As Long
        Dim dhcHKeyCurrentUser As Long
        Dim PDFPath As String
        Const dhcRegSz As Long = 1
        'Workbooks.Open ("\\master\fnshares\bcbcm\Client Management\Client Services\New Account Fees\09 September 2010\3Q10 Rebate Ltrs\Infi\MacroTest\A02.xls")
        Workbooks.Open ("H:\A02.xls")
        Select Case ActiveWorkbook.Sheets.Count
            Case 1
                Sheets(1).Select
            Case 2
                Sheets(Array(Sheets(1).Name, Sheets(2).Name)).Select
            Case 3
                Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name)).Select
            Case 4
                Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name, _
                 Sheets(4).Name)).Select
            Case 5
                Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name, _
                 Sheets(4).Name, Sheets(5).Name)).Select
            Case 6
                Sheets(Array(Sheets(1).Name, Sheets(2).Name, Sheets(3).Name, _
                 Sheets(4).Name, Sheets(5).Name, Sheets(6).Name)).Select
        End Select
        dhcHKeyCurrentUser = &H80000001
        strDefaultPrinter = Application.ActivePrinter
        'The directory in which you want to save the file
        PDFPath = ActiveWorkbook.Path & Application.PathSeparator
        'Change the pdf file name if required. This should have the fully qualified path
        strOutFile = PDFPath & Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & ".pdf"
        lngRegResult = RegOpenKeyA(dhcHKeyCurrentUser, "Software\Adobe\Acrobat Distiller\PrinterJobControl", _
            lngResult)
        lngRegResult = RegSetValueEx(lngResult, Application.Path & "\Excel.exe", 0&, dhcRegSz, _
            ByVal strOutFile, Len(strOutFile))
        lngRegResult = RegCloseKey(lngResult)
        ThisWorkbook.ActiveSheet.PrintOut copies:=1, ActivePrinter:="Adobe PDF"
        'ThisWorkbook.ActiveSheet.PrintOut copies:=1, preview:=False, ActivePrinter:="Adobe PDF", _
            printtofile:=True, collate:=True, prtofilename:=strOutFile
        'Call printToPdf(strOutFile)
        Application.ActivePrinter = strDefaultPrinter
        ActiveWorkbook.Close False
    End Sub
    Sub printToPdf(PDFFilename)
        ' Define a postscript file name
        PSFileName = "H:\TempPostScript.ps"
        ' Print the Excel range to the postscript file
        'Dim MySheet As Worksheet
        'Set MySheet = ActiveSheet
        ActiveWindow.SelectedSheets.PrintOut copies:=1, preview:=False, ActivePrinter:="Adobe PDF", _
            printtofile:=True, collate:=True, prtofilename:=PSFileName
        ' Convert the postscript file to .pdf
        Set myPDF = CreateObject("PdfDistiller.PdfDistiller.1")
        myPDF.FileToPDF PSFileName, PDFFilename, ""
    End Sub
    Values of my Variables When I Run the Code
    ? dhcHKeyCurrentUser
         -2147483647
    ? strDefaultPrinter
         \\tcps01p\FNT12W00 Canon 5020 PCL 5e on Ne04:
    ? PDFPath
         H:\
    ? strOutFile
         H:\A02.pdf
    ? lngResult
         2280
    ? Application.Path & "\Excel.exe
         C:\Program Files\Microsoft Office\OFFICE11\Excel.exe
    ? dhcRegSz
         1
    ? Len(strOutFile)
         10
    ? PSFileName
         H:\TempPostScript.ps
    ? PDFFilename
         H:\A02.pdf
    Values of my Registry Entries (HKEY_CURRENT_USER\Software\Adobe\Acrobat Distiller\PrinterJobControl)
    (Default)          REG_SZ          (value not set)
    C:\Program Files\Microsoft Office\OFFICE11\Excel.exe          REG_SZ          H:\A02.pdf
    LastPdfPortFolder - EXCEL.EXE          REG_SZ          "Q:\Client Management\Client Services\New Account Fees\09 September 2010\3Q10 Rebate Ltrs\Infi\MacroTest
    Note:  There are a couple of other entries for documents that I've printed manually that I didn't include.  Also, the last entry above, contains the value of the folder that I last manually "printed" to.
    I've also noticed that I have a Registry SubKey under PrinterJobControl called DownloadFonts.  However, the only entry there is:
         (Default) REG_SZ (value not set)
    Is this the registry key you mentioned, Reinhard?
    As you can see in my code, I have 3 different methods that I've tried to print.  The first one defaults everything after selecting the Acrobat PDF printer.  The second sets the output filename as a PDF (basically what you suggested, Karl Heinz).  The third method calls a procedure that prints to a PostScript file & then uses Distiller to print from that file to pdf.  This is the method Reinhard suggested.
    With the first 2 methods, I get NO error messages, but no file(s) show up.  With the 3 method, I get the error about the Fonts checkbox, but it creates a 0K PostScript file.  When I skip that statement and run the other 2 statements, I get a log file that says the PostScript file is empty and not PDF file was created.
    YIKES...  What's going on?  Thanks again for attempting to help me!!!
    Nate

  • Problem with controlling Annotations from Excel VBA

    Hi,
    I have a PDF document that has plenty of sticky notes attached to it. These sticky notes have been added by multiple authors on all pages of the document. I am trying to import the contents of these sticky notes, their author and the page number to an excel spreadsheet.  I am using Excel 2007 and Acrobat Professional 9.0.
    This is the code that I am currently using to import the sticky notes, but the problem that I am facing is that when I run the macro -
    Same sticky note contents, author and page numbers are imported multiple times
    Not all sticky notes are imported, only some of them appear in the final excel spreadsheet
    When I compare the number of sticky notes to that in the original PDF file, the number is correct. But the content is repeated content and that is the reason why only some of the sticky notes are imported.
    This is an activity that I need to do on regular basis and the number of sticky notes that I need to import to excel may range between 100 to 200. It is really difficult to do this task manually, so an excel VBA macro could prove really helpful.
    Sub ImportComments_Click()
    Dim Fpath As String
    Dim WordObj As Object
    Dim wbkOutput As Excel.Workbook
    Dim iRow As Integer
    Dim i, j, k As Integer
    Dim lRet As Long
    Dim objAcroAVDoc As New Acrobat.acroAVDoc
    Dim objAcroPDDoc As Acrobat.AcroPDDoc
    Dim numPages As Long
    Dim lAnnotscnt As Long
    Dim Subtype As String
    Dim NumComments As Long
    Dim AcroApp As Acrobat.AcroApp
    Dim objAcroPDPage As Acrobat.AcroPDPage
    Dim annot As Acrobat.AcroPDAnnot
    Sheets("Defect Log").Select
    Range("L3").Activate
    Fpath = ActiveCell.Value
    Sheets("Defect Log").Select
    Range("A1").Activate
    i = 0
    Do While (Not (IsEmpty(ActiveCell.Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 1).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 2).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 3).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 4).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 5).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 6).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 7).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 8).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 9).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 10).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 11).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 12).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 13).Value)) Or Not (IsEmpty(ActiveCell.Offset(0, 14).Value)))
    i = i + 1
    ActiveCell.Offset(1, 0).Select
    Loop
    iRow = i + 1
    Set wbkOutput = ActiveWorkbook
    lRet = objAcroAVDoc.Open(Fpath, "")
    Set objAcroPDDoc = objAcroAVDoc.GetPDDoc
    numPages = objAcroPDDoc.GetNumPages()
    Set objAcroPDPage = objAcroPDDoc.AcquirePage(0)
    For k = 1 To numPages
    lAnnotscnt = objAcroPDPage.GetNumAnnots()
    For m = 0 To lAnnotscnt - 1
    If lAnnotscnt = 0 Then Exit For
    Set objAcroPDAnnot = objAcroPDPage.GetAnnot(m)
    If (objAcroPDAnnot.GetContents <> "" And objAcroPDAnnot.GetSubtype = "Text") Then
    Cells(iRow, 5).Value = k
    Cells(iRow, 2).Value = objAcroPDAnnot.GetContents()
    Cells(iRow, 11).Value = objAcroPDAnnot.GetTitle()
    iRow = iRow + 1
    End If
    Next m
    Set objAcroPDPage = objAcroPDDoc.AcquirePage(k)
    Next k
    lRet = objAcroAVDoc.Close(1)
    Set objAcroAVDoc = Nothing
    Set objAcroPDAnnot = Nothing
    Set objAcroPDPage = Nothing
    Set objAcroPDDoc = Nothing
    End Sub

    Make sure you are current with 9.x patches, just on general principles.
    The code seems fine – nothing jumping out at me.
    You can also look at using the JSObject methods and trying this via the JavaScript stuff – that will give you more access to the Annotation information…
    From: Adobe Forums <[email protected]<mailto:[email protected]>>
    Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
    Date: Thu, 24 Nov 2011 04:25:12 -0800
    To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
    Subject: Problem with controlling Annotations from Excel VBA
    Problem with controlling Annotations from Excel VBA
    created by apreeti<http://forums.adobe.com/people/apreeti> in Acrobat SDK - View the full discussion<http://forums.adobe.com/message/4044740#4044740

  • Call Transaction from Excel VBA macro and download ALV list object results

    I have a situation that must be very common u2013 but I canu2019t find any clear information on how to get it done! 
    We frequently run SAP transactions, download the results (orders or inventory) into Excel, do some calculations and create a spreadsheet report. 
    I would like to automate this process using Excel VBA so that a macro will perform these steps:
    1. Run our custom SAP report "YSD033" that summarizes orders using the previous day as the [From Date] parameter.  (The user already has an active ECC 6 R3 session running.)   If possible, can the TC be run using a specific variant "G111BIZ" ?
    2. Download the list object that appears in an ALV grid as a table to an empty spreadsheet in the active workbook (export XXL list object)
    3. Save the resulting workbook and close Excel.
    Should the solution use u201Ccall transactionu201D or a GuiXT script?
    Any help would be much appreciated, and some sample VBA code would be great!
    Thanks.
    Glenn

    Good suggestion, but
    I get "permission denied" for   SapGuiAuto.GetScriptingEngine
    I also tried the method below, but received this RFC error message:
    User PPPPPPP  has no RFC authorization for function group SYST.
    Sub LoginCheck()
    If login = False Then
        ' Setting the necessary variables for R/3 connection
        Set objBAPICortrol = CreateObject("SAP.Functions")
        Set objConnection = objBAPICortrol.Connection
        ' Establish a connection
    If objConnection.Logon(0, False) Then
        login = True
        MsgBox "Connection Established"
        CommandButton1.Caption = "Disconnect"
    End If
    Else
        CommandButton1.Caption = "Connect 2 SAP"
        login = False
        objConnection.Logoff
        Set objConnection = Nothing
        Set objBAPICortrol = Nothing
    End If
    End Sub
    I was told that these kinds of authority open up too big of a window that can't be monitored adequately...
    I'm considering an approach like what is below if I can't convince security to grant me permissions...
        Application.Wait Now + TimeValue("00:00:01")
        SendKeys EnterKey, False
    Since blocked RFC security settings are preventing the solution from being installed, I am markgin this question as answered. 
    I will post different questions about 1. how to convince the security team that it will be safe to allow the use of RFC calls, and /or 2. how use some windows-level scripting code to run the SAP jobs.
    Thanks.
    Edited by: GlennWebster on Mar 1, 2010 4:34 PM

  • Need to checkout MS Project file from Excel VBA

    I have a VBA Excel macro that can open an MS Project file, and extract data.  It works fine when the MS Project file is on my hard drive or other location where no check out is required.  But often the MPP files I need to access are stored in SharePoint,
    in document libraries, that have checkin/checkout enabled.  I am aware of the the way to do this for an Excel file, such as the following code snippet.
     ' Determine if workbook can be checked out.
     If Workbooks.CanCheckOut(Filename:=docCheckOut) = True Then
      Workbooks.CheckOut (Filename:=docCheckOut)
     Else
      MsgBox "You are unable to check out this document at this time."
     End If
    I need to be able to do the same thing for MPP files.  Here is the code I have; however, I get a compile error on the CheckOut line, indicating "wrong number of arguments or invalid property assignment".  My research suggests that I should
    get this compile error, as it only works on certain collections.  Even the line containing "CanCheckOut", while it does not give me a compile or run time error, it does not return the proper response.
     Dim mpApp As MSProject.Application
     Set mpApp = New MSProject.Application
     AppActivate "Project Professional"
     ' Determine if mpp file can be checked out.     
     If mpApp.CanCheckOut(mppFileToOpen) = True Then
      mpApp.CheckOut (mppFileToOpen)
         Else
             MsgBox "Unable to check out this document at this time."
        End If
    Is there a way to checkout an MS Project file stored in SharePoint from within Excel VBA?  Thanks.
    Ray

    Rod,
    Thanks very much.  This was, indeed, the solution.  Don't know how I could have missed this.  
    I did run into some issues with ensuring proper object references, checking back in, and being able to handle files that may be on a laptop, SharePoint site with checkout requirements, or SharePoint site without checkout requirements.  Also faced an
    issue checking back in; part of my macro opens the MPP file (that is checked out), acquires various pieces of data, then runs a macro in the MPP file that exports data to an excel spreadsheet.  After this macro runs (does a save-as using a map), check
    in is no longer possible.  Fortunately, I could checkout the MPP file, open it, get all the required data elements, make a few changes to the MPP file, check it back in (but not close), then run the macro, then close without saving.  In the end,
    it all works like a champ.  Thanks very  much for your advice.
    Ray

  • How to use loop in VBAK table using BDC RFC connection through excel vba ?

    Hello,
    I am trying to extract data from VBAK table using rfc connection with Excel VBA. where i can able to pull data first time, when i tried to use the same set of code using loops, it throws an error like BAD INDEX.
    Any help appreciated.

    Hello,
    I am trying to extract data from VBAK table using rfc connection with Excel VBA. where i can able to pull data first time, when i tried to use the same set of code using loops, it throws an error like BAD INDEX.
    Any help appreciated.

  • RFC CALL VIA EXCEL VBA

    Hello,
    Hope someone call help with the following.
    I am trying to retrieve data from a table within SAP by using the following Excel VBA code.
    Sub retrieve_table_contents()
    Dim R3, MyFunc, App As Object
    Dim SEL_TAB, NAMETAB, TABENTRY, ROW As Object
    Dim Result As Boolean
    Dim iRow, iColumn, iStart, iStartRow As Integer
    iStartRow = 4
    Worksheets(1).Select
    Cells.Clear
    'Create Server object and Setup the connection
    Set R3 = CreateObject("SAP.Functions")
    R3.Connection.System = "QA2"
    R3.Connection.client = "900"
    R3.Connection.user = "mbrough"
    R3.Connection.password = "st34lh"
    R3.Connection.language = "EN"
    If R3.Connection.logon(1, False) <> True Then
       Exit Sub
    End If
    'Call RFC function TABLE_ENTRIES_GET_VIA_RFC
    Set MyFunc = R3.Add("TABLE_ENTRIES_GET_VIA_RFC")
    Dim oParam1 As Object
    Dim oParam2 As Object
    Dim oParam3 As Object
    Dim oParam4 As Object
    Set oParam1 = MyFunc.exports("LANGU")
    Set oParam2 = MyFunc.exports("ONLY")
    Set oParam3 = MyFunc.exports("TABNAME")
    Set oParam4 = MyFunc.Tables("SEL_TAB")
    oParam1.Value = "E"
    oParam2.Value = ""
    oParam3.Value = "LAGP"
    If frmQuery.txtSelect <> "" Then
        oParam4.Rows.Add
        oParam4.Value(1, "ZEILE") = frmQuery.txtSelect
    End If
    Result = MyFunc.CALL
    If Result = True Then
      Set NAMETAB = MyFunc.Tables("NAMETAB")
      Set SEL_TAB = MyFunc.Tables("SEL_TAB")
      Set TABENTRY = MyFunc.Tables("TABENTRY")
    Else
        MsgBox MyFunc.EXCEPTION
        R3.Connection.LOGOFF
        Exit Sub
    End If
    Result = R3.TABLE_ENTRIES_GET_VIA_RFC(EXCEPTION, LANGU:="E", ONLY:="", TABNAME:="LAGP", SEL_TAB:=SEL_TAB, NAMETAB:=NAMETAB, TABENTRY:=TABENTRY)
    'Quit the SAP Application
    R3.Connection.LOGOFF
    If Result <> True Then
      MsgBox (EXCEPTION)
      Exit Sub
    End If
    'Display table header
    iColumn = 1
    For Each ROW In NAMETAB.Rows
        Cells(iStartRow - 1, iColumn) = ROW("FIELDNAME")
    '   For C and N datatypes, explicitly set the cell to TEXT format, otherwise leading zeroes will be lost
    '   when numbers are imported from a SAP text field
        If ROW("INTTYPE") = "C" Or ROW("INTTYPE") = "N" Then
            Range(Cells(iStartRow - 1, iColumn), Cells(iStartRow - 1 + TABENTRY.Rowcount, iColumn)).Select
            Selection.NumberFormat = "@"
        End If
        Cells(iStartRow, iColumn) = ROW("FIELDTEXT")
        iColumn = iColumn + 1
    Next
    Range(Cells(iStartRow - 1, 1), Cells(iStartRow, NAMETAB.Rowcount)).Font.Bold = True
    'Display Contents of the table
    iColumn = 1
    For iRow = iStartRow + 1 To TABENTRY.Rowcount
        For iColumn = 1 To NAMETAB.Rowcount
            iStart = NAMETAB(iColumn, "OFFSET") + 1
    '       If this is the last column, calculate the length differently than the other columns
            If iColumn = NAMETAB.Rowcount Then
                iLength = Len(TABENTRY(iRow, "ENTRY")) - iStart
            Else
                iLength = NAMETAB(iColumn + 1, "OFFSET") - NAMETAB(iColumn, "OFFSET")
            End If
    '       If the fields at the end of the record are blank, then explicitly set the value
            If iStart > Len(TABENTRY(iRow, "ENTRY")) Then
                Cells(iRow, iColumn) = Null
            Else
                Cells(iRow, iColumn) = Mid(TABENTRY(iRow, "ENTRY"), iStart, iLength)
            End If
        Next
    Next
    'Format the Columns
    Range(Cells(iStartRow, 1), Cells(iStartRow + TABENTRY.Rowcount, NAMETAB.Rowcount)).Select
    Selection.EntireColumn.AutoFit
    End Sub
    However when I run the code I get the following exception message. 'SYSTEM_FAILURE' and nothing is returned.
    Does anyone know why this is?
    Thanks,
    Mike

    You can send data from excel to the MII message listener with a simple http post.
    Message format requirments can be found here:
    [http://help.sap.com/saphelp_xmii120/helpdata/en/45/6a86ac88130dece10000000a11466f/content.htm|http://help.sap.com/saphelp_xmii120/helpdata/en/45/6a86ac88130dece10000000a11466f/content.htm]
    Edited by: Christian Libich on Aug 10, 2009 10:14 PM

  • Getting clusters from LabVIEW ActiveX Server with Excel/VBA

    Hello,
    my colleague and I are trying to control a LV from Excel (VBA) by ActiveX.
    I.E.:
    We do something like :
    Set LV = createObject("LabVIEW.Application")
    Set VI = LV.GetVIReference("Path_to_VI")
    ParamNames(0) = "Input1"
    ParamNames(1) = "Input2"
    ParamNames(2) = "Output"
    ParamValues(0) = 1
    ParamValues(1) = 3.1415
    Call VI.Call(ParamNames,ParamValues)
    msgbox("output =" & ParamVals(2))
    This works perfectly for simple data types (int, double, float, string, etc )
    Now we need to transfer more complex structures, which are originaly LV-clusters.
    But we did not find any clue on how do that (especially receive clusters) in the help or on the internet.
    Is there any chance to succeed ???
    TIA,
    Thomas

    Actually, working with clusters is really really easy. Through the magic of - well something - a cluster in LV comes out in the VBA environment as an array of variants. There was an activex example that shipped with V7.1 that showed this very thing. I couldn't find them in V8 so here is the 7.1 stuff.
    Check out the macros in the Excel spreadsheet... This show running the VI in the development environment, but if this looks interesting I can fill you in on how to make it work in an executable.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps
    Attachments:
    freqresp.xls ‏49 KB
    Frequency Response.llb ‏155 KB

  • Problem with SQL Query in Excel VBA

    I am trying to retrieve data from a SQL table using Excel VBA.  The query will only return data from the first field in the query.  this is the code I am using:
    objGroupConn.Open
    Set objGroupCmd.ActiveConnection = objGroupConn
    objGroupCmd.CommandText = "SELECT GroupName, GroupNotes, GroupTotal, ArrivalTime" _
    & " FROM dbo.tblGroups" _
    & " WHERE((tblGroups.VisitDate)= '" & vdate & "')"
    objGroupCmd.CommandType = adCmdText
    objGroupCmd.Execute
    Set objGroupRecordset.ActiveConnection = objGroupConn
    objGroupRecordset.Open objGroupCmd
    ActiveSheet.Range("BN5").CopyFromRecordset (objGroupRecordset)
    objGroupRecordset.Close
    objGroupConn.Close
    The query is asking for information from 4 fields and only returns GroupName.  Any ideas?

    Hi GAMinTN,
    I can't reproduce your problem, if I created the same table as yours, I can successfully retrieve the data from the table and copy to the specified range.
    I recommend that you firstly check if the table in the database contains the proper data in all the 4 columns. Since the command text can be executed successfully and get the data of one column, it should be able to get the data from the other columns.
    Also please debug your code, check if the objGroupRecordset contains the proper data, and try to execute the SQL statement directly in the Sql Server, make sure the SQL statement is correct.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Calling UDF (MS Access) from Excel VBA

    Hi,
    I need to run a query on an MS Access database that has to perform a weekday calculation between two date columns,
    and this query has two date parameters that it receives dynamically. I am using Excel VBA as the front end.
    Select AgeRange, count(*) from
    (Select IIF(networkdays(date1,date())<=2, "0-2 days","over 2 days")) as AgeRange
    from table1
    where date2 >= startdt
    and date2 <=enddt
    ) d
    group by AgeRange
    The actual query is more complex, but this will help illustrate the issue. I build a string variable with
    the query, and substitute Startdt and enddt variables with the actual values. I then create a new QueryDef object and get the results from OpenRecordSet.
    Except, Networkdays is not a valid function in MS Access. So, this query fails.
    I created a WorkDays UDF in MS Access, and used that instead - the query works fine in MS Access, but when
    I try to pass it in the QueryDef object, it fails with 3085 error (function not available).
    I'm not sure how to get around this, and could use some help.
    In summary, I need to run a select query that will calculate weekdays or workdays between two columns (query
    is dynamic - dates are variable) from VBA to MS Access, get the results back to VBA so that I can populate the results. Any suggestions are appreciated and welcome.
    Thanks!
    I tried using datediff with the "w" parameter, but that doesn't work as I had hoped - it gives the
    number of weeks between the dates instead of weekdays
    I realize that I could get all the data (without doing the group by) down into Excel and then, do the networkdays
    formula calculation there, and summarize after that, but that is a very inefficient way - and defeats the purpose of having an access database in the first place. Getting tens of thousands of records is going to cause space issues in Excel too.

    Hi Bob,
    One solution is to create a table in the Access database storing all the dates in these years, add a column to determine if this date is a week day or not. And create another table to store the dates that are to be excluded from the working days.
    In this way, you need to create a separate query to count the valid working days based on the two tables. So the most difficult thing is to create the table that contains all the dates, please check this VBA code snippet which helps you to insert all the
    dates into the table.
    Sub InsertDatesIntoTable()
    Dim StartDate As Date
    Dim EndDate As Date
    Dim d As Date
    Dim w As Integer
    Dim IsWorkDay As Boolean
    StartDate = #1/1/2015#
    EndDate = #12/31/2015#
    For d = StartDate To EndDate
    Debug.Print d
    w = Weekday(d, vbSunday) 'first day of the week is Sunday
    If w = 1 Or w = 7 Then ' if the current day is Sunday or Satuday
    IsWorkDay = False
    Else
    IsWorkDay = True
    End If
    'Here you can insert d and IsWorkDay into the table
    Next d
    End Sub
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for

  • MS Access Cfquery or Cfstoredproc parameters declaration?

    How do you pass more than one argument to MS Access stored procedure (query) using either CFQuery or CFStoredProc? Environment: MS Access 2007; Coldfusion 7 Std Edition. Working example CFQUERY with 1 date value parameter: <cfquery name="testStoredPr

  • J1IS in subcontracting with full payment of excise duty

    hi Can u tell me please In subcontracting with full payment of excise duty I have created PO,sent material to stock provided to vendor (541).while creating outgoing excise invoice with referance to material doc.(MATD) i am getting following error. GL

  • Drag and drop to build a filter?

    What do people think of the idea: Drag a photo or photos into the filter area to quickly build a filter? You could drag a photo into the date area to grab all of the photos by that date, or into the keyword area to grab all the keywords. Multiple pho

  • Load balancing among multiple CPU

    I am using a java based application on windows server 2008 r2 64bit and JRE 6u17.The server has multiple processor.But when we run the application only one cpu takes the 100% load and cant balance the load.But if we run the application on windows xp

  • Third Party Interface

    Hi Experts. I want some clarification, we are implementing BPM - Solution Manager. I was checking the BPM Monitors Catalog. I didnt find any thirdparty interface monitoring. Our client has SAP and it has got some thirdparty interface such as Vertex,