HypRetrieve returns -3 Excel VBA
I've written some VBA code to run a macro inside my Excel 2007 worksheet. I'm using Hyperion Smart View version 9.3.1.2.029. Here's the code I created to refresh my worksheet:
Sub refreshData()
'FileSystem.FileCopy "C:\ExpenseFcstDownload\Expense_Forecasting.txt", "C:\ExpenseFcstDownload\Expense_Forecasting_Previous.txt"
'Application.ScreenUpdating = False
Dim costCenterRowStart As Integer
Dim costCenterColStart As Integer
Dim costCenterCell As range
Dim forecastRowStart As Integer
Dim forecastColStart As Integer
Dim forecastCell As range
Dim fileName As String
Dim delimiter As String
Dim append As Boolean
Dim rollup As String
Dim i As Integer
costCenterRowStart = 2
costCenterColStart = 1
forecastRowStart = 6
forecastColStart = 1
fileName = "c:\Expense_Forecasting.txt"
delimiter = "|"
append = False
i = 0
Set costCenterCell = getCell(costCenterRowStart, costCenterColStart, Sheet4)
Set forecastCell = getCell(forecastRowStart, forecastColStart, Sheet2)
connect
While costCenterCell.Offset(i, 0) <> ""
range(forecastCell, forecastCell.End(xlDown)).Clear
'Sheet4.Select 'Cost Center Sheet
costCenterCell.Offset(i, 0).Copy
'Sheet2.Select 'Forecast Sheet
'forecastCell.Offset(0, 1).Select
range(forecastCell.Offset(0, 1), forecastCell.Offset(0, 1).End(xlDown)).Offset(0, -1).PasteSpecial (xlPasteValues)
'Range(forecastCell.Offset(0, 1).Address, forecastCell.Offset(0, 1).Address.End(xlDown)).Select
'Range(forecastCell.Offset(0, 1), forecastCell.Offset(0, 1).End(xlDown)).Offset(0, -1).PasteSpecial (xlPasteValues)
forecastCell.Offset(0, 7).Formula = "=VLOOKUP(TRIM(B6),'ACCOUNT MAPPING'!$A$5:$B$291,2,FALSE)"
forecastCell.Offset(0, 7).Copy
' forecastCell.Select
range(forecastCell, forecastCell.End(xlDown)).Offset(0, 7).PasteSpecial (xlPasteFormulas)
'Application.Wait Time + TimeSerial(0, 0, 30)
'do the refresh
While Len(forecastCell) = 12
retrieve
Set forecastCell = getCell(forecastRowStart, forecastColStart, Sheet2)
Wend
'Application.Wait Time + TimeSerial(0, 0, 30)
Set forecastCell = getCell(forecastRowStart, forecastColStart, Sheet2)
forecastCell.Offset(0, 7).Formula = "=VLOOKUP(TRIM(B6),'ACCOUNT MAPPING'!$A$5:$B$291,2,FALSE)"
forecastCell.Offset(0, 7).Copy
' forecastCell.Select
range(forecastCell, forecastCell.End(xlDown)).Offset(0, 7).PasteSpecial (xlPasteFormulas)
'Sheet2.Select
'forecastCell.Select
'range(forecastCell, forecastCell.End(xlToRight)).Select
'range(forecastCell, forecastCell.End(xlDown)).Select
'export to txt
append = i
exportText forecastCell, fileName, delimiter, append
'forecastCell.Offset(0, 7).Select
range(forecastCell.Offset(0, 7), forecastCell.End(xlDown)).Offset(0, 7).Clear
'forecastCell.Select
range(forecastCell, forecastCell.End(xlDown)).Clear
i = i + 1
Wend
disconnect
Application.ScreenUpdating = True
Workbooks(1).Save
'FileSystem.FileCopy "C:\ExpenseFcstDownload\Expense_Forecasting.txt", "P:\Expense\Load_Data\Expense_Forecasting.txt"
Application.Quit
Public Sub connect()
Dim x As Long
x = HypConnect("Forecast Data", "user1", "1234", "EssbaseSpendExpense")
End Sub
Public Sub disconnect()
Dim x As Long
x = HypDisconnect("Forecast Data", True)
End Sub
Public Sub retrieve()
Dim x As Long
x = HypRetrieve("Forecast Data")
End Sub
If I step through my code (F8), it works fine. If I try to run the macro by itself (F5), the HypRetrieve will randomly return -3. I've noticed that it seems to fail more often when I'm multitasking. If I keep the spreadsheet focused and don't move the mouse, it will sometimes work. I couldn't find any error description for -3 except that it's a local failure. I know others have gotten this type of error but I couldn't find out how they resolved it.
Thanks.
Just a guess but make sure the active sheet is the one where you want to perform the retrieve.
Even though the first parameter is for sheet name, currently the VBA macros ignore that setting and default to the active sheet. Sheetname is a placeholder parameter for future use.
Similar Messages
-
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 BreiReinhard & 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 -
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.
RayRod,
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 -
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,
MikeYou 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 -
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. -
Powershell Variable from Excel.VBA Macro
Hi Guys!
I don't know if what i'm asking you is achievable.
I've learned how to pass variables/arguments from powershell to Excel/VBA Macro but i need to do the opposite thing.
This is an example of what i want:
Powershell
Excel/VBA Macro
$Input=1 ----------------------------------------------------------------> Sub Macro(input)
$excel.Run("Macro",$Input)
Output=input +6
$output (Expected 7) <---------------------------------------------------- return Output
I don't know how to do this can you help me please?
AOk guys those are the script.
Macro:
Sub CreatePWD()
Dim PWD As String
Dim i As Integer
Dim Max As Integer
Dim F1 As Worksheet
Set F1 = ThisWorkbook.Worksheets("Foglio1")
Max = F1.Range("A1").Value
For i = 1 To Max
If Int((2 * Rnd) + 1) = 1 Then
PWD = PWD & Chr(Int((90 - 65 + 1) * Rnd + 65))
Else
PWD = PWD & Int((9 - 0 + 1) * Rnd + 0)
End If
Next i
MsgBox PWD
End Sub
Powershell:
$Excel = New-Object -ComObject excel.application
$Excel.visible=$false
$Version = "C:\Users\Alberto Corona\Desktop\Cartel1.xlsm"
$WorkBook= $Excel.workbooks.open($Version)
$WorkSheet= $WorkBook.worksheets.item(1)
$WorkSheet.cells.item(1,1)=5
$Excel.Run("CreatePWD")
$WorkBook.save()
$WorkBook.close()
$Excel.quit()
The result of macro is like "52UT7" i want a variable in powershell called $PWD that contain the value of the macro.
Hope the problem is clear now.
Thanks
A -
Adobe Javascript from within Excel VBA
I have some limited experience with Excel VBA and Adobe Javascript separately, but have never tried to put them together. I am rather baffled by the use of “DoJavaScript” from within Excel VBA. I have a number of Illustrator JavaScripts that do various tasks (mostly measure and set properties on illustrator drawing objects to determine some geometric metrics). I wanted to run these scripts from within Excel VBA (they run without problem when directly called into Illustrator). My hope was to pass a few real numbers from VBA into the JavaScript before one ran to set some run parameters and then get a few real numbers back out from the JavaScript back into VBA. I cannot seem to get even the simple DoJavaScript command given in the Adobe VBscript reference to run. Reading other posts that seem somewhat related it is not clear if I am doing something very simple wrong, or if my understanding of the use of the DoJavaScript command is misguided. Anyone able to shed some light on this?
My last try was this simple test...almost directly from the Adobe reference:
Private Sub SetScale_CommandButton1_Click()
Set appRef = CreateObject("Illustrator.Application")
Set myNumberOfDocuments = appRef.DoJavaScript("documents.length;")
MsgBox myNumberOfDocuments
End Sub
I am really hoping to be able to run javascripts that are a few hundred lines long....but if I cannot even get something simple to go then I am about to give up on it.
Thanks for any suggestionsCarlos;
I am most grateful! ... I was stumped on that for hours, thought I had tried about every combinatory possible, and was about to give up on getting the DoJavaScript method to work. There are few examples of this on the web, so for anyone else who would like a bit more verbose example I post below is a simple VBA sub-routine that uses a javascript function to return the number of selected objects in the current active illustrator document and displays that number in a message box in excel. Simple example, but it was the sort if thing I was looking for all over the web before Carlos’ help.
Cheers,
Brian
Private Sub ObjectNum()
Set appRef = CreateObject("Illustrator.Application")
tmp$ = "function myfunction() {"
tmp$ = tmp$ + "var idoc = app.activeDocument;"
tmp$ = tmp$ + "var sel = idoc.selection;"
tmp$ = tmp$ + "var numobj = sel.length;"
tmp$ = tmp$ + "return numobj;};"
tmp$ = tmp$ + "myfunction();"
numobj = appRef.DoJavaScript(tmp$)
MsgBox numobj
End Sub -
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...
  
This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs. -
How to delete formula from cells and keep the values in Excel VBA
Hi,
In my Excel I have 15 columns. In column F which has a formula (INDEX MATCH), it has contains "RECEIVED" and "INTRANSIT". I need to filter the column F for all "RECEIVED" and then remove the formula from cells and
retain or keep the values that are already in the cells. something tricky and i'm not sure on how to work on this in Excel VBA.
Below is my initla VBA code:
I already have the codes on how to filter. kindly please help me on how to do this. thank you in advance.
Sub test_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim lrow As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets("Intransit_")
Application.ScreenUpdating = False
ws.AutoFilterMode = False
With ws
lrow = .Range("F" & Rows.Count).End(xlUp).Row
Set rng = .Range("A1:R" & lrow)
Debug.Print rng.Address
rng.AutoFilter Field:=6, Criteria1:="RECEIVED"
End With
Application.creenUpdting = True
End SubSolved.
Sub test_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim lrow As Long
Dim rRec As Range
Dim btField As Byte
Set wb = ThisWorkbook
Set ws = wb.Sheets("Intransit_")
btField = 6
Application.ScreenUpdating = False
ws.AutoFilterMode = False
With ws
lrow = .Range("F" & Rows.Count).End(xlUp).Row
Set rng = .Range("A1:R" & lrow)
With rng
.AutoFilter Field:=btField, Criteria1:="RECEIVED"
On Error Resume Next
Set rRec = .SpecialCells(xlCellTypeVisible)
On Error GoTo 0
End With
.AutoFilterMode = False
If Not rRec Is Nothing Then
With rRec
.Columns(btField).Value = .Columns(6).Value
End With
End If
End With
Application.ScreenUpdating = True
End Sub -
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 solversGordons 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 -
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 -
How to call a labview dll from excel-VBA?
How to call a simple Labview DLL from Excel VBA?
I have seen examples of DLL calls from VB but does it work the same way for VBA? I have 2000 excel and Labview 8.5. I created the DLL and tried to call it from VBA using the same type of code as in NI's website example(ofcourse its a bit diff with 8.5)
http://zone.ni.com/devzone/cda/tut/p/id/...
BUT it errors out when called from excel
ERROR: The object invoked has disconnected from its clientYou would need to provide more details about the LabVIEW DLL, such as the prototypes of the functions (VIs) that you're trying to call, and your actual VBA code. Specifically, what object you're trying to create. You should also make sure the Run-Time Enginer is installed, as well as any required libraries such as the VISA Run-Time if you're using VISA. Have you made sure to enable the ActiveX server for the DLL?
A search yielded the following items that you may wish to peruse:
http://forums.ni.com/ni/board/message?board.id=170&message.id=261345&requireLogin=False
http://forums.ni.com/ni/board/message?board.id=170&message.id=45099&requireLogin=False
http://forums.ni.com/ni/board/message?board.id=170&message.id=299209&requireLogin=False
http://forums.ni.com/ni/board/message?board.id=170&message.id=195846&requireLogin=False -
Excel VBA to JS: How does one pass rectangle coordinates to a JS function.
I have an Excel VBA sub that calls a folder level JS function and I'm trying to pass a set of rectangle coordinates.
This is the VBA code:
Sub BarcodeDoc_PDF417(pdfFileName As String)
Dim AVDoc As Acrobat.CAcroAVDoc
Dim PDDoc As Acrobat.CAcroPDDoc
Dim myApp As Acrobat.CAcroApp
Dim jso As Object
Dim bcTmpFile As String
bcTmpFile = "C:\Temp\bcTmpFile.pdf"
Set myApp = CreateObject("AcroExch.App")
Set AVDoc = CreateObject("AcroExch.AVDoc")
If AVDoc.Open(pdfFileName, "") Then
Set PDDoc = AVDoc.GetPDDoc
Set jso = PDDoc.GetJSObject
jso.myAdd417Barcode 'This is where the coordinates get passed.
PDFSave PDDoc, bcTmpFile
myApp.CloseAllDocs
myApp.Exit
Set AVDoc = Nothing
Set jso = Nothing
Set PDDoc = Nothing
Set myApp = Nothing
Else
MsgBox "Sub: BarcodeDoc_PDF417. Document not found:" & vbCrLf & vbCrLf & pdfFileName
End If
End Sub
This is the folder level JS script:
function myAdd417Barcode(myCoords)
//The line below is just for testing. Will come out once I can pass the coords in from my VBA sub.
//var myCoords = [324, 756, 540, 720];
InsertPDF417Barcode(this, myCoords);
I've tried to pass the coords as a string and an array, both to no avail. Any ideas?
Thanks.I tried typing the array as a variant (in the VBA code), but the JS script didn't like that either.
I then changed the JS script to this:
function myAdd417Barcode(n1, n2, n3, n4)
var bcCoords = [n1, n2, n3, n4];
InsertPDF417Barcode(this, bcCoords);
and passed it 4 integers thinking it would accept them in a way that I could then define the rectangle coordinates as shown above. It didn't work, and the error I get is that myCoords (in the script below) "isn't defined".
var InsertPDF417Barcode = app.trustedFunction( function(doc, mycoords)
app.beginPriv();
var bcIconFileName = "/C/Temp/bcTmpImage.pdf";
//var bcCoords = [324, 756, 540, 720];
var t = doc.addField("bcFormID", "button", 0, myCoords);
t.display = display.visible;
t.buttonPosition = position.iconOnly;
t.buttonScaleHow = scaleHow.proportional;
t.buttonScaleWhen = scaleWhen.always;
t.buttonFitBounds = true;
t.setButtonIcon
var x = doc.importIcon("myIcon", bcIconFileName, 0);
var f = doc.getField("bcFormID");
var i = doc.getIcon("myIcon")
var y = f.buttonSetIcon(i);
app.endPriv();
Any suggestions will be appreciated.
Thanks! -
Acrobat 9.0 Standard. Setting PDF file password from Excel VBA
Acrobat 9.0 Standard. Setting PDF file password from Excel VBA
Hi: I am trying to find a call to set the password of a PDF file that I am creating from Excel Workbook using a VBA call.
I basically have this Excel VBA code that works fine and creates a file.
pBook.PrintOut Copies:=1, preview:=False, ActivePrinter:="Adobe PDF", _
PrintToFile:=True, collate:=True, PrToFileName:=PSFileName
' Convert the postscript file to .pdf
Dim myPDF As PdfDistiller
Set myPDF = New PdfDistiller
myPDF.FileToPDF PSFileName, "", ""
BUT, I need to set the password on this PDF file and do not see an option to do so.
Can you provide a solution for this situation? Appreciate your response in advance.
Thanks.There is no way to set password programmatically using any other dll or any other kit?
I am creating a bunch of PDF files for users programmatically but then they have to go in and set password themselves? This is very inconvenient for users. -
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,
MikeIs there no way of connecting the tables within the code.
IT won't give me access to SE11
Thanks,
Mike
Maybe you are looking for
-
i continually get the same 12.0a2 update box that pops up in the bottom right corner even though i have the updated version and i have to wait for the aurora updater to do something everytime i start a new session. i went through and disabled all plu
-
Indesign CS4 Export PDF Crash/Quits
Hi all, I am part of a small company, we recently bought CS3 Design Standard for 3 new G5 Intel Core 2 Duo 2.66 Ghz iMacs, all have 2GB 800MHz DDR2 SDRAM memory, but sadly Illustrator and Indesign just kept quitting, so we were forced to updrade to C
-
OID/Portal - Restrict Special Characters to be used in Password
Hi, Does anyone know how I can restrict the use of special characters ($, &, £...etc) in the OID password? I cannot see an attribute to achive this? orclpwdIllegalValues will stop certain words, but I just want to restrict the use of any of the speci
-
Multiple line items in ESERVICE table
Hi All, In production they moved out one BP from a premise and Moved in another BP in that premise.Now when they reverse both Move In and Move out they are getting multiple line items in ESERVICE table.In our case two shipper was created.How to avoid
-
Sub contracting GR cancellation
Dear All, I have done GR for sub contracting PO, when I am doing return delivery for that material document system is throwing the error as Deficit of Stock w. vendor unr. 500 EA : RO00106781 BP01 O Message no. M7021 Kindly Guide me how to proceed? R