dynamically select sheet from the inputprompt and print to a file - vba

i have 3 sheets in my workbook namely sheet1 ,sheet3 and sheet2 when i enter a values from in the inputpromt say (eg:1,2 ) i split it and store it in an array it must dynamically select the sheet1 and sheet2 and print values to a file.
i have done a pseudo below can any one
Sub example()
Dim Ran As Range
Dim cnt as String
Open "D:\temp\test.txt" For Output As #1
Dim myarray() As String
Dim holder As String
dim ab as Strig
ab="this is sample data"
holder = InputBox("Enter your choice eg:1,2")
myarray = Split(holder, ",")
Dim name, country,birth As String
For i = 1 To UBound(myarray)
If i = 1 Or i = 2 Then
name = Sheets(i).Range("Z12").Value
country= Sheets(i).Range("PQ26").Value
birth = Sheets(i).Range("ab24").Value
ab=ab & name & country & birth
Print #1, ab
End If
Next i
end Sub
****in the inputbox if i give value as 1,2 then it must select values from sheet 1 and sheet2****

I am guessing you that you are trying to understand InputBox and how to split a string such as “1, 2” and process the separate values as sheet numbers.
Sheet numbers mean nothing to the user so I do not believe this is a good approach. You need to offer the user a list of worksheet tabs from which they can select.
There is InputBox and Application.InputBox. These are different and I do not like either. They come from the earliest versions of VB and were probably originally a direct match to MS-DOS’s console input. With one exception, there are much better approaches. The one exception is the ability to input a range with Application.InputBox for which I do not know a convenient alternative.
In the code below I use InputBox. You may think I have overdone the validation but what if the user enters “A”? Your code would assume “A” was a sheet number but Excel would assume it was a worksheet name and stop execution with a subscript error. You must check for any error that will cause your code to stop with a run-time error.
Instead of either InputBox you should use a User Form. There are on-line tutorials to get you started. With a User Form you have several choices including:
A List box, with multiple selection enabled, containing the names of every permitted worksheet.
A column of radio buttons, one per permitted worksheet. These would be unlinked so the user could select several.
A command button for each permitted worksheet which the user could click in turn.
All of these choices are much user-friendlier than InputBox.
Step through the code below with F8 and study what it does. Come back with questions if necessary but the more you can understand on your own the faster you will develop.
Option Explicit
' Please indent your macros consistently. This makes them much easier ri read
Sub example()
Dim Ran As Range
Dim cnt As String
Dim myarray() As String
Dim ab As String
' Variables I have added or which are replacements for yours.
Dim Answer As String
Dim AllValuesGood As Boolean
Dim InxMA As Long
Dim InxSht As Long
Dim Question As String
' I like to keep all my Dim statements together at the top.
' This makes them easier to find.
Dim name, country, birth As String
' I have output to the Immediate window which is simpler when
' experimenting.
'Open "D:\temp\test.txt" For Output As #1
Question = "Enter your choice eg: ""1"" or ""1,2"""
' You omitted the code to check the Answer
Do While True
Answer = InputBox(Question, "Experiment with Input box")
' Have a string but user could have typed anything
If Answer = "" Then
' Cannot tell if user has clicked Cancel or if user clicked Return
' before entering value. Have to assume Cancel
Debug.Print "User clicked Cancel"
Exit Sub
Else
AllValuesGood = True ' Assume good answer until find otherwise
myarray = Split(Answer, ",")
For InxMA = 0 To UBound(myarray)
If IsNumeric(myarray(InxMA)) Then
InxSht = Val(myarray(InxMA))
If InxSht < 1 Or InxSht > 2 Then
' Sheet number outside permitted range
AllValuesGood = False
Exit For
End If
Else
' Non-numeric sheet number
AllValuesGood = False
'Debug.Assert False
Exit For
End If
Next
End If
If AllValuesGood Then
' Have good answer. Exit Do-Loop to print sheets
Exit Do
Else
' An invalid sheet number has been found
Question = "Click cancel to exit or enter ""1"" or ""2"" or ""1, 2"""
' Loop to repeat Input
End If
Loop ' Until have good answer
' If get here Answer is a list of good sheet number
For InxMA = 0 To UBound(myarray)
InxSht = Val(myarray(InxMA))
' I have not created sample worksheets with data in Z12, PQ26 and ab24
' but this shows the code you need
'With Worksheets(InxSht)
' name = .Range("Z12").Value
' country = .Range("PQ26").Value
' birth = .Range("ab24").Value
'Next
name = "Name" & InxSht
country = "Country" & InxSht
birth = "Birth" & InxSht
' Have to initialise ab here because need new value per sheet
ab = "this is sample data"
ab = ab & name & country & birth
Debug.Print ab
' The value of ab will be messy because you have no spaces between words.
'Print #1, ab
Next InxMA
End Sub

Related

Catia V5 Macro: Incomplete renaming function

I've been dealing with this a while and even had help but i can't work it out.
The following macro renames PartName or InstanceName depending on user and CADSelection.
Problem is it's not working in PartName alteration.
Can someone help me complete this macro? and ideally explain what i did incorrectly?
Sub CATMain()
If CATIA.Documents.Count = 0 Then
MsgBox "There are no CATIA documents open. Please open a CATIA document and try again.", ,msgboxtext
Exit Sub
End If
If InStr(CATIA.ActiveDocument.Name, ".CATProduct") < 1 Then
MsgBox "The active document is not a Product. Please open a CATIA Product and try again.", ,msgboxtext
Exit Sub
End If
Dim oSelection As Selection
Set oSelection = CATIA.ActiveDocument.Selection
If oSelection.Count < 1 then
MsgBox "Pick some components using cad selection."
Else
'****** Alter Instance Name *****'
Dim msg
msg = MsgBox ("Click ""Yes"" to change Instance Name, ""No"" to change Part Name or ""Cancel"" to exit", _
vbYesNoCancel, "Renaming Tool")
if vbYes = msg then
'****** Inputbox for Instance name alteration *****
Dim NewIName As String
NewIName = InputBox("Please input the desired Instance Name. Example: E","Instance name alteration","E")
'****** Inputbox for Instance number alteration *****
Dim NewINumber As Integer
NewINumber = InputBox("Please input the initial number for the 1st component. Example: 1","Instance numbering alteration","1")
Dim oIBody
Dim InstName As Body
For oIBody = 1 to oSelection.Count
Set InstName = oSelection.Item(oIBody).Value
'****** Instance name alteration *****
InstName.Parent.Parent.ReferenceProduct.Products.Item( _
InstName.Name).Name= NewIName + CStr(NewINumber)
NewINumber=NewINumber+1
Next
elseif vbNo = msg then
'****** Inputbox for Part name alteration *****
Dim NewPName As String
NewPName = InputBox("Please input the desired Part Name. Example: E","Part Name alteration","E")
'****** Inputbox for Part number alteration *****
Dim NewPNumber As Integer
NewPNumber = InputBox("Please input the initial number for the 1st Component. Example: 1","Part numbering alteration","1")
Dim oPBody
Dim PartName As Body
For oPBody = 1 to oSelection.Count
Set PartName = oSelection.Item(oPBody).Value
'****** Part name alteration *****
PartName.ReferenceProduct.Name= NewPName + CStr(NewPNumber)
NewPNumber=NewPNumber+1
Next
End If
End If
oSelection.Clear
End Sub
The part "name" is really the Part Number and is changed using the "PartNumber" property.
So try changing
PartName.ReferenceProduct.Name= NewPName + CStr(NewPNumber)
to
PartName.ReferenceProduct.PartNumber= NewPName + CStr(NewPNumber)
This doesn't influence the document name unless you have not saved your part already.
What else :
1) Your variable naming is confusing. You call the Product "InstName" in one place and "PartName" in another. At first glance I thought those were strings. Using oProduct would be less confusing.
2) You seem real confident that the user has pre-selected the correct types. Since you are selecting in an assembly, instead of using Selection.Item(i).Value, you can use Selection.item(i).LeafProduct which will always be the instance product of whatever object is selected. Even if the user picks a surface, it will return the instance product which contains the selected surface.

VBA Form - Vlookup cell and assign value to that cell

Encountering an issue in a VBA regarding vlookup function.
I have 2 comboboxes and 6 Textboxs for user input.
I want to use a vlookup (or index,Match(),Match()) to look up a cell in a data table and assign the values from the textboxes to these cells.
When I run the code for what I believe should work, it is returning object errors.
Private Sub CommandButton2_Click()
Dim MonthlyTable As Range
Set MonthlyTable = Sheets("DATA Monthly").Range("A6:AE400")
Dim ColumnRef As Range
Set ColumnRef = Sheets("Drivers").Range("N11")
' Assign CB2 value to M11 cell reference so it can be converted to a column ref in N11.
Sheets("Drivers").Range("M11").Value = ComboBox2.Value
Dim CB1Value As String
CB1Value = "Joiners" & ComboBox1.Value
Dim CB2Value As String
CB2Value = ComboBox2.Value
MsgBox CB1Value & " " & CB2Value
Dim tb1value As Range
tb1value = Application.WorksheetFunction.VLookup(CB1Value, MonthlyTable, ColumnRef, False)
tb1value.Value = TextBox1.Value
Unload Me
End Sub
I am at a loss for what to do here as I feel like it should be this simple!
Thanks in advance.
Edit. Further digging indicates that you cannot select a cell you are vlookup'ing as this commands only returns a value it does not actually select the cell for my intents and purposes.
not really clear to me you actual aim, but just following up your desire as stated by:
I want to use a vlookup (or index,Match(),Match()) to look up a cell
in a data table and assign the values from the textboxes to these
cells
you may want to adopt the following technique:
Dim tb1value As Variant '<--| a variant can be assigned the result of Application.Match method and store an error to be properly cheeked for
tb1value = Application.Match(CB1Value, MonthlyTable.Column(1), 0) '<--| try finding an exact match for 'CB1Value' in the first column of your data range
If Not IsError(tblvalue) Then MonthlyTable(tb1value, columnRef.Value).Value = TextBox1.Value '<--| if successful then write 'TextBox1' value in data range cell in the same row of the found match and with `columnRef` range value as its column index
Excel uses worksheet functions to manipulate data, VBA has different tools, and when you find yourself setting cell values on a sheet via VBA so that some worksheet function can refer to them it is time to look for a true VBA solution. I suggest the following which, by the way, you might consider running on the Change event of Cbx2 instead of a command button.
Private Sub Solution_Click()
' 24 Mar 2017
Dim MonthlyTable As Range
Dim Rng As Range
Dim Lookup As String
Dim Done As Boolean
Set MonthlyTable = Sheets("DATA Monthly").Range("A2:AE400")
' take the lookup value from Cbx1
Lookup = ComboBox1.Value
Set Rng = MonthlyTable.Find(Lookup)
If Rng Is Nothing Then
MsgBox Chr(34) & Lookup & """ wasn't found.", vbInformation, "Invalid search"
Else
With ComboBox2
If .ListIndex < 0 Then
MsgBox "Please select a data type.", vbExclamation, "Missing specification"
Else
TextBox1.Value = MonthlyTable.Cells(Rng.Row, .ListIndex + 1)
Done = True
End If
End With
End If
If Done Then Unload Me
End Sub
There are two points that need explanation. First, the form doesn't close after a rejected entry. You would have to add a Cancel button to avoid an unwanted loop where the user can't leave the form until he enters something correct. Note that Done is set to True only when the search criterion was found And a value was returned, and the form isn't closed until Done = True.
Second, observe the use of the ListIndex property of Cbx2. All the items in that Cbx's dropdown are numbered from 0 and up. The ListIndex property tells which item was selected. It is -1 when no selection was made. If you list the captions of your worksheet columns in the dropdown (you might do this automatically when you initialise the form) there will be a direct relationship between the caption selected by the user (such as "Joiners") and the ListIndex. The first column of MonthlyTable will have the ListIndex 0. So you can convert the ListIndex into a column of MonthlyTable by adding 1.
I think it is better to use "find" in excell vba to select a cell instead of using vlookup or other methods.

find out cell address having = sheet name

I'm just a beginner for VBA but advance in MS excel. that's why I am very much interested to learn VBA.
ok this is my first question here
Actully i need to format excel sheet where file name is = sheet1 name and it is somewhere in column "A" so I want to select & delete all the rows above this cell & below untill there is a blank cell/row.
I have tried much with InStr & find function but no succeed. Also try to find cell address like B5 but could no do that.
Welcome to StackOverflow. As you have already been informed by newguy, when posting a question you should also show what you have tried so far... some piece of code, printscreens, etc.
Your explanation was not that clear (at least to me), but based on what I have understood, I have made a small code sample for you to get you started. I have broken down the code into the function blocks, so that you can better understand what they are trying to achieve.
Here is the code:
'the following function will find cell with the specific text
Private Function FindCell(ws As Worksheet, strToSearch As String, Optional sColumn As String = "A") As Integer
Dim iCounter As Integer
'as you do not know where exactly it exists, we loop from first cell in the particular row
'to the very last celll
With ws
For iCounter = 1 To .Range("A65000").End(xlUp).Row ' or .UsedRange.Rows.Count, or any other method
If .Range(sColumn & iCounter).Value = strToSearch Then
'yay, we have found the cell!
'pass out the reference
FindCell = iCounter
'now call exit function as we no longer need to continue searching for the cell (we have already found it!)
Exit Function
End If
Next iCounter
End With
'in case the cell does not exist, we can return -1
FindCell = -1
End Function
'the following cell will search the very first cell to the top (starting from specific row), which is blank / empty
Private Function FindEmptyCell(ws As Worksheet, iStartRow As Integer, Optional sColumn As String = "A") As Integer
'This function does the same, as if you have selected specific cell
'and then pressed left Ctrl + Up arrow at the same time
'Try it!
'You can do the same with Right + Left + Bottom arrow as well
FindEmptyCell = ws.Range(sColumn & iStartRow).End(xlUp).Row + 1
End Function
Private Sub EraseRows()
Dim iStartCell As Integer
Dim iEndCell As Integer
On Error GoTo 0
'First let's find the "bottom" cell which is the cell with the specific text you are looking for
iEndCell = FindCell(ActiveSheet, "TextIAmLookingFor")
'now let's see find the top blank cell (so that we get the range of from - to that you want to erase)
iStartCell = FindEmptyCell(ActiveSheet, iEndCell)
'now we can delete the rows!
'iEndCell-1 because you don't want to erase the cell with your search string, right?
ActiveSheet.Rows(CStr(iStartCell) & ":" & CStr(iEndCell - 1)).EntireRow.Delete (xlUp)
End Sub

What VBA coding in a Userform can I use to find a cell based upon row & column content, and then update that cell?

I am a complete beginner to VBA, truely.
I am trying to create a user form that will update the number of tasks a person completes on a given date as listed on a spreadsheet. I envision the Userform having two bottons (which are hidden and appear as the conditions of the subroutine). I am working on a Mac, by the way, and I know that will have VBA coding implications for use on a PC och vice versa.
The example sheet is this:
The example Userform (a) is this:
For argument's sake, let say I want to update or input the number of tasks that Greg completed on the 7th of May (2013/05/07).
I would like for the Userform to proceed something like this:
Entering person and date:
Then, retrieving number of tasks for Greg on the 7th after button click:
Now, I want to input that I know Greg completed 6 tasks on the 7th and I click the second button (now visible and the first button hidden):
And the result in the spreadsheet:
I ought to input some code here, but my skills and the completeness of the code are wanting. But I will put in what I have:
Option Explicit
'Subroutine when clicking the first ("find") button
Private Sub btnfind_Click()
lbltasks.Vissible = True
txttasks.Visible = True
btnupdate.Visible = True
btnfind.Visible = False
'Defining variables
Dim pr01 As String
Dim dt01 As Date
Dim tsk01 As Integer
'Assigning variables to inputs
pr01 = txtperson.Text
dt01 = txtdate.Text
tsk01 = txttask.Text
'Looking for Name in column "A"
' ? ? ?
'Looking for inut Date in row "1"
' ? ? ?
'Retrieving the existing number of tasks according to name and date
'and showing number in the 'tasks' text input box in the user form
' ? ? ?
End Sub
'Subroutine when clicking the Second ("update") button
Private Sub btnupdate_Click()
'Paste updated Number of tasks in appropriate cells according to name and date
'The new number of tasks should over write what was there previously
' ? ? ?
End Sub
Thanks in advance for any and all help!
This should work. Please study it and use the macro record function in Excel to grasp a lot more:
Option Explicit
Public frmName As Variant 'store row of name
Public frmDate As Variant 'store column of date
'Subroutine when clicking the first ("find") button
Private Sub btnfind_Click()
'Defining variables
Dim pr01 As String
Dim dt01 As Date
Dim tsk01 As Integer
'Assigning variables to inputs
pr01 = UserForm1.TextBox1.Text
dt01 = UserForm1.TextBox2.Text
tsk01 = UserForm1.TextBox3.Text
'Looking for Name in column "A"
With ThisWorkbook.Worksheets("Sheet4")
frmName = .Columns("A").Find(pr01).Row
End With
'Looking for inut Date in row "1"
With ThisWorkbook.Worksheets("Sheet4")
frmDate = .Rows(1).Find(CDate(dt01)).Column
End With
If frmName Is Nothing Or frmDate Is Nothing Then
'not found
Exit Sub
End If
'Retrieving the existing number of tasks according to name and date
'and showing number in the 'tasks' text input box in the user form
With ThisWorkbook.Worksheets("Sheet4")
UserForm1.TextBox3.Text = .Cells(frmName, frmDate)
End With
End Sub
'Subroutine when clicking the Second ("update") button
Private Sub btnupdate_Click()
'Paste updated Number of tasks in appropriate cells according to name and date
'The new number of tasks should over write what was there previously
With ThisWorkbook.Worksheets("Sheet4")
.Cells(frmName, frmDate) = UserForm1.TextBox3.Text
End With
End Sub

copy row data from one sheet to one or more sheets based on values in other cells

I have a sheet with user details in columns A - C.
Columns D-H is distribution lists the users are subscribed too. (currently check box linked to cell to indicate which list(s) user is subscribed to)
A user can be subscribed to more than on list.
At the moment I can use filters which works ok to filter users for list x, copy the user info to another sheet, then next list filterd (used text for the list selection)
This does cause some problems between some of the users of this sheet.(those that don't know how to use filters)
I would like to create a new sheet for each list which gets populated automatically.
As a user is added/removed from a list, his details is automatically added/removed from the corresponding 'list sheet'.
This way no one can complain about the filters
At the same time they can then export the 'list sheet' they require to another xls doc or csv as required.
I have found various options on how to do this, but all of then had only one selection column. I thought I could alter some of the ranges etc etc in the sample code but all failed with the limited knowledge I have with VB.
Any suggestions on how to do this?
Thanks!
Please do not try and create two copies of your data. Keeping two versions of the same data in step is very, very difficult.
I believe your best option is to create a macro with which your users can select the filter they require.
You do not describe your data in much detail so I have imagined something like the following:
Name Addr Tele List1 List2 List3 List4 List5
John London 1234 x
Jane Paris 2345 x
Kevin Stockholm 3456 x
Mary Brussels 4567 x
Nigel Dublin 5678 x
Abby Athens 6789 x x x
Brian Rome 7890 x
Given the above layout, the following macro shows the sort of thing I would offer.
When the macro is executed, it displays an InputBox like this:
from which the user can select the filter required.
I hope this gives you some ideas.
Option Explicit
Sub SelectFilter()
Dim ColNum() As Variant
Dim InxList As Long
Dim ListName() As Variant
Dim Prompt As String
Dim ReturnValue As Variant
' Load ListName with user-friendly names for the lists
ListName = Array("Name list 1", "Name list 2", "Name list 3", _
"Name list 4", "Name list 5")
' Load ColNum with the column number for each list. The entries in ColNum
' must be in the same sequence as the entries in ListName. Column "A" is
' column 1, column "B" is column 2 and so on.
ColNum = Array(4, 5, 6, 7, 8)
' Combine the user-friendly list names to create a menu
Prompt = ""
For InxList = 0 To UBound(ListName)
Prompt = Prompt & InxList + 1 & ". " & ListName(InxList) & vbLf
Next
Prompt = Prompt & "Please enter the number against the list you require." _
& vbLf & "Leave box empty to cancel selection."
' Loop until user cancels or enters a permitted value
Do While True
ReturnValue = InputBox(Prompt, "Select filter")
If VarType(ReturnValue) = vbBoolean Then
If Not ReturnValue Then
' The documentation for InputBox claims it returns False if
' the user clicks Cancel. In my experience it return a
' null string but check to be on the safe side.
Exit Sub
Else
' True is not a documented return value from InputBox.
' This code should never be executed but if something
' goes wrong there is a message for the user.
Call MsgBox("Please report there has been a InputBox " & _
"error type 1 to Chaka", vbCritical)
Exit Sub
End If
End If
If VarType(ReturnValue) <> vbString Then
' False or a string are the only documented return values
' This code should never be executed but if something
' goes wrong there is a message for the user.
Call MsgBox("Please report there has been a InputBox " & _
"error type 2 to Chaka", vbCritical)
Exit Sub
End If
If ReturnValue = "" Then
' User has clicked cancel or left the text box empty.
Exit Sub
End If
If IsNumeric(ReturnValue) Then
InxList = ReturnValue - 1
If InxList >= 0 And InxList <= UBound(ListName) Then
' Good selection
Exit Do
End If
End If
Loop
With Sheets("Sheet2")
If .AutoFilterMode Then
' AutoFilter is on. Cancel current selection before applying
' new one because criteria are additive.
.AutoFilterMode = False
End If
.Cells.AutoFilter Field:=ColNum(InxList), Criteria1:="x"
End With
End Sub
A simple solution, hope this helps
Here's a simple solution I figured:
Copy the top row with the heading from the main sheet to all the
sheets
Paste this formula in field A2 of each sheet: ='MainSheet'!A2:I555 (number
555 can be increased as per requirement)
Drag this first row-wise, then column-wise till the end
In the top row with the heading, filter the data as per your requirement, for e.g. in the MainSheet, data can be filtered on any column on any value needed
Do this for all the sheets
When you update the data in the MainSheet, just re-run the filter to refresh the data
HTH,