Runtime error 424 VBA excel - excel

I've had a some success creating a project script that throws up some dialogues to take information, place it on a worksheet (activex box) and then print.
My code runs fine when located in Sheet1 object with the VB editor. However, I want it to run on excel open, so I paste it into the thisworkbook object within workbook_open(), but nothing works.
Can anyone explain to me how I can get this script to run upon excel open, or cease to receive the 424 error when running it from workbook_open()?
The debugger doesn't like my labelbatch and labelexpiry objects (but only when in thisworkbook), but it works fine otherwise.
Private Sub Workbook_Open()
ActiveWorkbook.Sheets("sheet1").Activate
'Clears label fields prior to data entry
labelbatch.Caption = ""
LabelExpiry.Caption = ""
'Auto input of batch code into batch field using input text.
BatchNo = InputBox("Enter batch code", " ")
labelbatch.Caption = BatchNo
'Auto input of expiry date into expiry field using input text.
ExpiryDate = InputBox("Enter expiry date", " ")
LabelExpiry.Caption = ExpiryDate
'Show print dialog box
Application.Dialogs(xlDialogPrint).Show
'Close without saving changes
ActiveWorkbook.Close False
End Sub

Assuming labelbatch and labelExpiry are objects on the worksheet, when the code is moved to ThisWorkbook VBA doesn't know where to look for those objects. Use e.g.
thisworkbook.worksheets("Sheet1").labelbatch
to refer to them.
When you use a method or property name without all its parents, VBA will either throw an error or will use a default depending on the context. For example, for Cells(), Range() and the like, that default is Application.ActiveSheet. That is generally risky: it's very hard to be sure what the active worksheet will be if you later change your code (or even if a user switches sheets while your code is running). Better to specify which worksheet you want.
This does make references to objects longer, but you can always use With...End With to help readability and save typing.

Related

Why additional excel window appears

Scenario
I am using a macro whereby I use Application.Visible = False to hide the workbooks. Also I use Application.Visible = True to unhide the workbook. At certain situation, I use Windows(ThisWorkbook.Name).Visible = False and Windows(ThisWorkbook.Name).Visible = True to hide and unhide only the workbook which contains macro.
Problem
I noticed during these operations, some additional excel windows(without any workbook) appear other than the workbook. Please see the picture below. You can see a grey window behind with a name Excel. That is the window I am talking about
If I closed that window, the whole excel will close. Does anyone know why this extra window appearing and how to prevent it from appearing?
I am not sure if this will meet the needs of your specific situation. But, what if you kept Application.Visible = False at the beginning of your code and changed Application.Visible = True to
Application.Windows(ThisWorkbook.Name).Visible = True at the end. This worked for me.
Hiding Excel
With the following code
Sub AppVisibleTrue
Application.Visible = True
End Sub
Sub AppVisibleFalse
Application.Visible = False
End Sub
you are showing or 'hiding' the 'whole' excel application, so you have to 'unhide' it in the same code, otherwise you won't be able to use the open files after you hide it, e.g. open a new workbook, in VBE add a new module and paste the above code into the module. Now, stay in VBE!!! Run the 'False' Sub. You will notice Excel has 'vanished', but you can still find it in the Task Manager's processes. Now run the 'True' Sub. Excel has 'reappeared'.
The following process will make Excel 'vanish'. The only way to close it will be via the Task Manager. If you not too familiar with doing this, just take my word for it.
Close the VBE. Now run the 'False' Sub. Excel has 'vanished'.
To conclude, this is obviously an error in your code, so I would suggest if you want to show a window (worksheet) that isn't 'ThisWorkbook' and you're dancing from one to the other, you should declare a variable
Const strSheet as String = "Sheet2"
Dim oSheet as Worksheet
'...
Set oSheet = ActiveWorkbook.Worksheets(strSheet)
Now you do with oSheet whatever you want.
Try to lose Active, Select and similar methods in the code.
If you would provide the actual scenario with the codes, a better assessment of the problem could be done.
The additional Excel window(s) could be related to your Windows Explorer. If you are previewing a document (in this case an Excel document) then the application to view that document is running in the background.
In this case, forcing the application to be visible will also make the background "preview" windows visible.

Paste/Copy Range of Cells from Excel to a Bookmark in Word using WORD VBA

I am looking at inserting/pasting a range of text data (40 columns) from Excel into bookmarks in Word. Most of the answers are done using Excel VBA, which is so not practical for my use case as I will have the Word document open, add a button that would run this 'import data' macro. I actually already have a button in the doc that inserts images into bookmarks, so that's one more reason I don't want to do it via Excel VBA.
I know this is not great code, but for the lack of definite leads, I'm throwing it here and hope that this gives you an idea of what I'm trying to achieve:
Sub ImportData()
Workbooks.Open ("\Book2.xlsm")
ActiveWindow.WindowState = xlMinimized
ThisWorkbook.Activate
Windows("Book2.xlsm").Activate
Range("A1:AF1").Select
Selection.Copy
Documents("test.docm").Activate
Selection.GoTo What:=wdGoToBookmark, Name:="Overlay_1"
Selection.Paste
End Sub
PS: It would be great if I could sort of 'transpose' the 40 columns into rows as it is pasted in Word.
Here's an update to my code based off #Variatus 's advice:
Sub ImportData()
Dim wb As Workbooks
Dim ws As Worksheets
Dim objSheet As Object
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
wb.Open ("C:\Users\pc\Documents\Book2.xlsm")
Set objSheet = CreateObject("Excel.Application")
ActiveWindow.WindowState = xlMinimized
Set ws = Workbooks("Book2.xlsm").Sheets("Sheet1")
ws.Range("A1").Value.Copy
With objWord.ActiveDocument
.Bookmarks("Bookmark_1").Range.Text = ws.Range("A1").Value
End With
End Sub
I'm getting this error:
Runtime Error '91':
Object variable or With block variable not set.
Notice how I stuck with a single cell reference for now (A1). I'll just update my code as I learn along the way :)
When you click the button in your Word document you want the following sequence to be initiated.
Create an Excel application object. Make sure that a reference to Excel has been set (VBE > Tools > References) so that Excel's VBA objects are available.
Using the Excel application object, open the workbook. Create an object. Place the object in an invisible window.
Definitely forget about activating or selecting anything in either the workbook or your Word document. The latter is active and remains active from beginning to end. The bookmarks are points in your document you can reference and manipulate by name without selecting them. The Excel workbook is invisible. You can access any part of it using the Range object.
The data you want from your workbook are contained in Worksheets. Be sure to create an object for the worksheet you are about to draw data from.
Excel tables don't translate very well into Word tables. If you do want to go that way I suggest that you use VBA to create the table you want in Excel (transpose the data before you import them into Word). However, you may find it easier to first create the tables you want in Word and then just copy values from your Excel source into the word tables. That would involve taking one cell value at a time and placing it into one Word table cell. Transposing would be done by the algorithm you employ.
Close the workbook. Quit the Excel application. Set the Excel application = Nothing. At the end of your macro everything is as it was before except that your document has data in it which it didn't have before.
Each of the above six points will lead you to at least one question which you can ask here after you have googled the subject and written some code. In fact, I strongly urge you to create one Main procedure (the one which responds to your button click) and let that procedure call various subs which carry out the individual tasks and functions to support the subs. The smaller the parts you create the easier it is to write the code, to find questions to ask and get answers to them. If you plan your project well expect to have about 12 procedures in it by the time you are done. Good luck!

Excel Macro, Sending user's data

So I am currently studying SQL Server but right now I am just working a standard office admin job while I'm studying.
I never really made macro's before and little knowledge on VB but decided to design a macro for work to make things a bit easier for my team.
The macro just very simply allows the user to enter data, stats etc and gives the percentage or average statistic resulting in a total letting the user know if the statistics have been hit that day, week, month etc.
It works well but I would like to add a "SUBMIT" button that when a user clicked it would send the data they have entered in specified cells to myself. I am not sure how to go about it, If needed I don't have access to systems like SQL, Visual Studio etc in work as said just basic admin job at the moment.
Would It need to be submitted as a CSV? or could it be submitted from the user's sheet straight onto another macro I have designed giving the results for the whole team? As said I am totally new to this idea.
Cheers Guys.
Awright, according to what you may need in a very simple approach, the first thing you need to do it's to know the cells where they're going to enter info (care with ranges ), let's assume for this example that whe only had one data entered in the first cell of the team worksheet. So, create a button called 'button1' or as you wish and on the click event use this code :
Private Sub button1_click()
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
End Sub
That would copy the value from one sheet to another, now, if you had you sheet locked via password, you must unlock it before doing that,then lock it again so code would be like this :
Private Sub button1_click()
On Error Resume Next
yoursheet.unprotect password:="yourpassword"
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
On Error Resume Next
yoursheet.PROTECT password:="yourpassword"
End Sub
I clarify that this is a very simple approach, so, if you're using specific cells you can copy one by one and this would do (so you can make anny calculation son your admin sheet), but when you're copying ranges should be like this :
Teamsheet.Range("A1:D3").Value = yoursheet.Range("A1:D3").Value
Also, always consider how they enter this data you need.
UPDATE :
Let's say you have a team workbook and yours is admin_workbook, concept it's similar. This code will do what you need but both workbooks should be at the same folder or path :
Private Sub button1_click()
Var_data = Teamsheet.Cells(row,column)
Application.ScreenUpdating = False
Workbooks.Open Filename:=ThisWorkbook.Path & "\admin_workbook.xls"
ThisWorkbook.Activate
Admin_sheet.Cells(destinyrow,destinycolumn) = var_data
Workbooks("admin_workbook.xls").Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
First you capture data on a var, then you open your admin book, put the data on the cell you want and close that workbook saving changes (you decide if you keep this line or mantain the workbook open and save manually). Also, Application.screenupdating it's a line that helps your screen doesn't flick when changing between workbooks.
Hope it helps friend !

Is it possible to automatically input VBA code when a new sheet is generated?

Is it possible to have a new Excel sheet created and then VB code automatically put in that sheet?
Here is what I have done so far. A sheet called Template has the input for all of the information that users need to input. I have various checks to make sure that all fields are filled out and are filled out correctly before anything else will execute. When they click on a certain cell to execute the script it will open a Word document and import all required information in it. Then a new sheet in Excel is created. A name is given to the new sheet, based on what was selected in the ComboBox (cboSites) from the Template sheet. I also have a check in place to make sure there already isn't a sheet with the same name. I have all of this working without any issues.
From here what I would like to do and can't think of how to do it, is when the new sheet is created I want VBA code automatically dumped in this new sheet. I know the code that I want to use, but I just have no idea how to get it so it will automatically put that code with that sheet.
Is this possible to do or can only a new sheet be created and formatted, without being able to import any code into it?
Here is a sample code which will insert
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
MsgBox "Hello World"
End Sub
in a new sheet in a new workbook.
Sub Sample()
Dim wb As Workbook, ws As Worksheet
Dim VBP As Object, VBC As Object, CM As Object
Dim strProcName As String
Set wb = Workbooks.Add
Set ws = wb.Sheets(1)
Set VBP = wb.VBProject
Set VBC = VBP.VBComponents(ws.Name)
Set CM = VBC.CodeModule
strProcName = "Worksheet_SelectionChange"
With wb.VBProject.VBComponents( _
wb.Worksheets(ws.Name).CodeName).CodeModule
.InsertLines Line:=.CreateEventProc("SelectionChange", "Worksheet") + 1, _
String:=vbCrLf & _
" Msgbox ""Hello World"""
End With
End Sub
Please amend it to suit your needs.
You need to ensure that Trust access to Visual Basic Project is selected. To select it, follow the steps mentioned in THIS LINK
I am not aware of an easy way to put code in an Excel file.
Someone might think about changing the XML structure directly (xlsx files are basically a zipped directory of xml and code files).
But did you consider using XLAM (Excel addin) files, that can contain code and be imported for all users, who ever need to use it. And would open up with Excel, when the users start it. Depending on your setup, this could help you?
Look into the VBProject property of the workbook you are generating. You should be able to manipulate it, adding new VBComponents items containing the code you want.
http://msdn.microsoft.com/en-us/library/office/ff194737.aspx
This will require the appropriate security settings to do.
Here's a thread on another site related to this topic:
http://www.mrexcel.com/forum/excel-questions/663848-access-vbulletin-project-not-trusted.html
I haven't tried it myself, so I can't give much more detail.

sub terminates but desired workbook not displayed

I have a VBA program that asks for the user to enter a desired range, which is in another opened workbook. If there is an error, i.e. the other workbook is manually activated, but no range is selected, or there is an error, I want the program to display the original macro workbook sheet with an error message. The code below works in Debug mode, but when the VBA program is run, it displays the error correctly but does not display the original macro worksheet. It remains on the sheet that was manually activated by the user. What am I missing?
In the code below, "HMArea" is a Range variable returned by the routine getting user input.
"Macro_Fname" is a string variable for the file name of the original VBA program.
HM_file = FileName(HMArea)
If HM_file = "Macro_Fname" Then
Windows("Macro_Fname").Activate
Sheets("[name of the sheet in Macro_Fname]").Select
Range("D4").Select
MsgBox "ERROR: No data selected"
Exit Sub
End If
Try changing
Windows("Macro_Fname").Activate
to
Workbooks("Macro_Fname").Activate
However, the exact nature of your question is vague. Assuming you are in Workbook A, do you want to select a range in Workbook B (which is open at the same time)?
To refer to macro workbook use ThisWorkbook
When another workbook is opened always assign it to variable so that you can have control over it.
Set wbk = Workbooks.Open("D:\test.xlsx")
When working with multiple workbook always prefix the workbook object. If its ignored it will take active workbook.
`Sheets("[name of the sheet in Macro_Fname]").Select`
Avoid using Select/Acitvate. See here
Range("D4").Select
Once the above issues are fixed your code will run as expected.

Resources