Waiting for user input - with DoEvents a good idea? - excel

My macro is going to compare a sheet with another sheet. This second sheet needs the user to paste data in there. (Note: The data being copied is not in Excel).
One way is to run the macro, and end it by prompting the user to paste the data in, then run "Macro2". However, I'd like to keep it all in one macro, so have found a way to wait for user input before continuing. This seems to work for me, so my main question is:
How stable is doing it this way?
...macro stuff above here
MsgBox ("[Please copy the data into the new sheet, after clicking 'OK']")
Do While WorksheetFunction.CountA(newWS.Cells(1, 7)) < 1
DoEvents
Loop
...then after the user pastes info, continue on, using the data that's been pasted.
The idea is that DoEvents just runs and runs while my sheet is blank. Right after the user pastes the data into the newWS, the macro continues on (since it will see data in column 7)...
Is this an okay method, or is it a bad idea to use like that? I've never really used DoEvents, so don't know if it's doing something in the background that could cause issues.
Edit: The data is in Lotus Notes, which I can export to Excel. However, that takes a few more steps (and I'd rather not create some new temporary excel files), so copy/pasting is my preferred method. This question is half practical, and half theoretical. Sorry for any confusion!

Probably not the best idea. Instead, allow them to select the data and perform the copy, all through VBA:
MsgBox ("[Please select data to copy into the new sheet, then press 'OK']")
newWs.Cells(1,1).PasteSpecial '### Modify to your specific location to paste the data
'Here you can add logic to validate that they have pasted enough data,
' and use control statement to prompt them to paste more data, etc.,
' if necessary, or exit sub early
'For example:
If WorksheetFunction.CountA(newWS.Cells(1, 7)) < 1 Then
MsgBox "Try again!"
Exit Sub
End If
Alternatively, you can use a DataObject:
Dim dataObj As New MSForms.DataObject
dataObj.GetFromClipboard
newWs.Cells(1,7).Value = dataObj.GetText

You could restructure the code so that it lives inside of a userform with ShowModal set to false (in the properties). Code prior to when you want the user to gather data can be put in the useform's initialize event. Then the userfrom shows (with a simple label caption and an okay button). Since it is modeless the user can copy data from an external program and paste it in. Then the rest of the code runs after the user hits okay. The form itself can be hidden during this phase. As proof of concept I created the following form:
with the following code:
Private Sub CommandButton1_Click()
Me.Hide
MsgBox Range("A1").Value
Unload Me
End Sub
Private Sub UserForm_Initialize()
'macro code can go here
'it runs before the form shows
'e.g.
MsgBox "Initializing"
End Sub
I launch the form on a blank sheet. First a message box appears before the code (confirming that code can run while the form is being initialized but before it is visible) then the form shows:
I go to an open instance of Notepad which contain a sentence and, while the form is still open -- paste it into A1:
Finally I press okay and the userform then hides itself but continues to run code (which now has access to the copied data):
Remember to unload the form at the end.

Related

Get command button by using cell address

I want to call/ activate a button at the end of a Sub. I know the cell address of the command button, but I don't know the name/ID of the button.
How do I select/activate the button without looping through each button on active sheet?
https://stackoverflow.com/a/30600479/13049793
I have created my buttons on multiple rows with each assigned to the same macro, from my understanding, I cannot call the macro the button is assigned to because the macro uses the button's relative position, below is a simple example to illustrate the use of the buttons relative position:
Sub ExampleButtonClick()
Dim Cellvalue As String
Cellvalue = ActiveSheet.Buttons(Application.Caller).TopLeftCell.Offset(0, -1).Value
Msgbox (Cellvalue)
End Sub
i assume you want to run one macro that at the end initiates a different macro, i also assume the reason the button is rather not as a sub that is just called is because it has its independent function that can be used without the other sub
assuming that you used a command button as an activeX control, why not just use a private sub that the button performs and place that in an individual module and at the end of your current sub;
call module1 'assuming the private sub exists in module 1
or rather include the code even if duplicated in the first sub, searching for a button seems the circular route unless there is another intention you wish to pursue.
maybe elaborate on the task at hand or post the current code you are working on?

How to create a code of clicking the button in VBA?

I have created a messagebox and coded so that the excel goes to the specific range where the button exists. But I do not know how to code so that the macro automatically clicks the button.
Sub Start()
Range("A4").Select
< >
End Sub
Sub MessageBox()
MsgBox "Hi" & vbCrLf & "Professor", _
vbInformation, "Greetings"
End Sub
I need something < > in this space but the process to automatically get linked.
Anyone have an idea?
In your example it looks like you have the name of the macro, and if that's the case it should be easy to just call it. See below
Sub Start()
Range("A4").Select
Call MessageBox
End Sub
Sub MessageBox()
MsgBox "Hi" & vbCrLf & "Professor", vbInformation, "Greetings"
End Sub
However, I'm guessing that doesn't help you because what you're asking doesn't truly make sense. I'm going to guess that maybe by MsgBox, you actually mean Form or Command Button. These look similar but they are distinctly different.
A MsgBoxis more of an alert to the user with the option to capture a small amount of information back (i.e. yes/no/ok/cancel etc). Clicking on a MsgBoxwill never directly launch another macro. An ANSWER to a MsgBox(i.e yes/no) MIGHT determine if another Macro is run based on an if-statement, or if the next line of code is simply just to execute another macro.
If you have a macro running distinctly based on a click, the button is likely a Form or an active X command Button. You need to figure out what macro this object is executing and then you just need to include this in your code. Google "how to see what macro a form button runs in VBA" or if it's an active X button, right click on it and hit "View Code". Both of these approaches should drive you to a macro name such as CommandButton1_Click.
Unfortunately, you might have to get more fancy as if it's a sheet Commandbutton1_Click you may have to make it public. Hopefully you can insert a call that code in your current macro.
Hope that helps.

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 !

Userform pops up if cell contains "2SO" or "2SQ"

I am trying to get a User form to appear if a cell in my spread sheet states either "2SQ" or "2SO" - both require the same User form. There is one text field on the User Form for the user to either input a number for example "0001" or a word such as "Various". Once the User enters in the data, there is an "OK" Command Button (CommandButton1) to press. I then want the data they put in the User form to go into another cell of the spread sheet.
I have already created the User form (UserForm1) however cannot get it to appear when require and obviously, I can't get it to transfer the data entered into another cell.
I would love to give you examples of what I have already tried however they are just copy and pastes from websites to try and make it happen with no luck
Try some VBA likme this in the Worksheet code:
Private Sub Worksheet_Change(ByVal Target As Range)
Select Case Target.cells(1, 1).Value
Case "2SQ", "2SO"
UserForm1.Show Modal:=True
Sheet.CellWhereYouWantItToGo.Value = UserForm1.TextBox1.Text
End Select
End Sub
The Modal part means the code will wait until the form is closed (i.e. in your ComandButton1 click event you must Me.Hide)

How to erase one region in Excel when closing the spreadsheet

I have a spreadsheet, with whatever in it. Now I want use one specific region (let's say C1:D10) to hold temporary data (in case I cannot remember clearly or mess them up).
However, I don't want keep the data for ever, and it is totally useless when this spreadsheet is used next time. Is there any way to erase this part when the spreadsheet is closed, no matter whether the user choose "save the change" or not, so that (C1:D10) is blank when I open the spreadsheet next time.
Instead of clearing the cells upon exit, use the Workbook_Open to clear the cells. This way you don't need to bother whether the user save the workbook on exit or not. This code will clear the cell the moment the workbook is opened.
Change Sheet1 below to the relevant sheet.
Private Sub Workbook_Open()
Sheets("Sheet1").Range("C1:D10").ClearContents
End Sub

Resources