Use ComboBox input to find itself in the workbook? - excel

I am new to VBA and UserForms.
I have a ComboBox where the user will enter a unique Sales Order # (SalesOrder). I want my form to take this input and find it in the workbook and then update the status with the user's inputs in later ComboBoxes (CommentBox & OrderStatus). The issue I am facing is the actual code to find the Sales Order # in the workbook. I've tried what is seen below in several different variations.
If I replace all the ComboBox inputs with the actual inputs as a string, the code runs fine in a module.
Ideally, the code will loop through the sheet array finding all the lines with the Sales Order # and apply the inputs to the row.
Sub AddDataToList()
Dim shtarray As Variant, shtname As Variant
Dim Data As Worksheet, ws As Worksheet
Dim wbk As Workbook
Dim Strg As String
shtarray = Array("EMAUX", "Irene", "Cassandra", "Patricia", "EMREL", "Maria", "Jason", "Peedie", "MICRO", "PARTS", "NAVY", "DELTA")
Set wbk = ThisWorkbook
For Each shtname In shtarray
Set ws = Nothing
On Error Resume Next
Set ws = wbk.Worksheets(shtname)
On Error GoTo 0
If Not (ws Is Nothing) Then
ActiveSheet.Cells.Find(StatusUpdateForm.SalesOrder.Text).Offset(0, 17).Select
ActiveCell.Value = CommentBox.Text
ActiveCell.Offset(0, 2).Value = OrderStatus.Text
End If
Next
MsgBox SalesOrder.Value & "was updated."
End Sub
Thank you for the assistance!
More Information ***
Below is the code for the Update command button. This is a standard two button system, one updates the records and the other cancels the form.
Private Sub UpdateButton_Click()
If Not EverythingFilledIn Then Exit Sub
Me.Hide
AddDataToList
Unload Me
End Sub
And code for the EverthingFilledIn
Private Function EverythingFilledIn() As Boolean
Dim ctl As MSForms.Control
Dim AnythingMissing As Boolean
EverthingFilledIn = True
AnythingMissing = False
For Each ctl In Me.Controls
If TypeOf ctl Is MSForms.TextBox Or TypeOf ctl Is MSForms.ComboBox Then
If ctl.Value = "" Then
ctl.BackColor = rgbPink
Controls(ctl.Name & "Label").ForeColor = rgbRed
If Not AnythingMissing Then ctl.SetFocus
AnythingMissing = True
EverythingFilledIn = False
End If
End If
Next ctl
End Function

Try this (my first comment notwithstanding):
Sub AddDataToList()
Dim shtarray As Variant, shtname As Variant
Dim Data As Worksheet, ws As Worksheet
Dim wbk As Workbook
Dim Strg As String
Dim r As Range
shtarray = Array("EMAUX", "Irene", "Cassandra", "Patricia", "EMREL", "Maria", "Jason", "Peedie", "MICRO", "PARTS", "NAVY", "DELTA")
Set wbk = ThisWorkbook
For Each shtname In shtarray
Set ws = wbk.Worksheets(shtname)
Set r = ws.Cells.Find(StatusUpdateForm.SalesOrder.Text) 'better to specify all parameters
If Not r Is Nothing Then
r.Offset(0, 17).Value = CommentBox.Text
r.Offset(0, 2).Value = OrderStatus.Text
End If
Next
MsgBox SalesOrder.Value & "was updated."
End Sub
There is no need to select things.

Related

Save Selected Sheets in another workbook

Wondering why I can't do :
For i = 1 To ThisWorkbook.Sheets.Count
If ThisWorkbook.Sheets(i).Name <> "DO NOT SAVE" Then ThisWorkbook.Sheets(i).Select Replace:=False
Next i
Selection.Copy
what would be the best way to save all sheets which does not match DO NOT SAVE name in another wb ?
Try this:
Sub Tester()
Dim ws As Worksheet, arr(), i As Long
ReDim arr(0 To ThisWorkbook.Worksheets.Count - 2)
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "DO NOT SAVE" Then
arr(i) = ws.Name
i = i + 1
End If
Next ws
Worksheets(arr).Copy
End Sub
A Reflection on the Sheets' Visibility
To export a single sheet to a new workbook, the sheet has to be visible.
To export multiple sheets (using an array of sheet names) to a new workbook, at least one of the sheets has to be visible, while very hidden sheets will not get exported (no error though).
In a given workbook, the following procedure will copy all its sheets, except the ones whose names are in a given array (Exceptions), to a new workbook if at least one of the sheets is visible.
Before copying, it will 'convert' the very hidden sheets to hidden and after the copying, it will 'convert' the originals and copies to very hidden.
Option Explicit
Sub ExportSheets( _
ByVal wb As Workbook, _
ByVal Exceptions As Variant)
Dim shCount As Long: shCount = wb.Sheets.Count
Dim SheetNames() As String: ReDim SheetNames(1 To shCount)
Dim sh As Object
Dim coll As Object
Dim Item As Variant
Dim n As Long
Dim VisibleFound As Boolean
Dim VeryHiddenFound As Boolean
For Each sh In wb.Sheets
If IsError(Application.Match(sh.Name, Exceptions, 0)) Then
Select Case sh.Visible
Case xlSheetVisible
If Not VisibleFound Then VisibleFound = True
Case xlSheetHidden ' do nothing
Case xlSheetVeryHidden
If Not VeryHiddenFound Then
Set coll = New Collection
VeryHiddenFound = True
End If
coll.Add sh.Name
End Select
n = n + 1
SheetNames(n) = sh.Name
End If
Next sh
If n = 0 Then
MsgBox "No sheet found.", vbExclamation
Exit Sub
End If
If Not VisibleFound Then
MsgBox "No visible sheet found.", vbExclamation
Exit Sub
End If
If n < shCount Then ReDim Preserve SheetNames(1 To n) ' n - actual count
If VeryHiddenFound Then ' convert to hidden
For Each Item In coll
wb.Sheets(Item).Visible = xlSheetHidden
Next Item
End If
wb.Sheets(SheetNames).Copy ' copy to new workbook
If VeryHiddenFound Then ' revert to very hidden
Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count)
For Each Item In coll
wb.Sheets(Item).Visible = xlSheetVeryHidden
dwb.Sheets(Item).Visible = xlSheetVeryHidden
Next Item
End If
MsgBox "Sheets exported: " & n, vbInformation
End Sub
Sub ExportSheetsTEST()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
ExportSheets wb, Array("DO NOT SAVE")
End Sub
Alternatively you could use the following snippet:
Sub CopyWorkbook()
Dim i As Integer
For i = 1 To ThisWorkbook.Sheets.Count
If ThisWorkbook.Sheets(i).Name <> "DO NOT SAVE" Then
Dim rng As Range
Windows("SOURCE WORKBOOK").Activate
rng = ThisWorkbook.Sheets(i).Cells
rng.Copy Before:=Workbooks("TARGET WORKBOOK").Sheets(i)
End If
Next i
End Sub

populate combobox from another workbook

How can I populate a combobox from another workbook, assuming that my data are in a worksheet named "affectation" and the data are in the 1st column
My combobox is in a userform, to fill it from the activeworkbook I use this code :
Private Sub CommandButton1_Click()
Dim ws_Liste_affect As Worksheet
Set ws_Liste_affect = ActiveWorkbook.Worksheets("affectation")
Fin_Liste_affect = ws_Liste_affect.Range("A65530").End(xlUp).Row
For i = 2 To Fin_Liste_affect
UserForm1.ComboBox_affect.AddItem ws_Liste_affect.Range("A" & i)
Next
UserForm1.Show
End Sub
I wan to fill it from another workbook.
I (only) suppose that you need to populate a combo box using data from a sheet of another workbook. If my understanding is correct, please try the next code:
Private Sub CommandButton1_Click__()
Dim ws_Liste_affect As Worksheet, Fin_Liste_affect As Long, arr As Variant
Dim wbFullPath As String, wb As Workbook, boolFound As Boolean
wbFullPath = "C:\...\TheOtherWorkbook.xls"
For Each wb In Workbooks
If wb.FullName = wbfullname Then
Set ws_Liste_affect = wb.Worksheets("the other sheet")
boolFound = True: Exit For
End If
Next
If Not boolFound Then
Set wb = Workbooks.Open(vbfullpath)
Set ws_Liste_affect = wb.Worksheets("the other sheet")
End If
Fin_Liste_affect = ws_Liste_affect.Range("A" & Rows.count).End(xlUp).Row
arr = ws_liste.affect.Range("A2:A" & Fin_Liste_affect).Value
UserForm1.ComboBox_affect.List = arr
UserForm1.Show
End Sub

How to create a Button that opens the previous excel sheet in VB.NET?

I want to create a Button that opens the previously opened excel sheet.What would be your Idea?
There is a code in VBA: Sheet(ActiveSheet.previos.Activate).select
I tried to translate this into vb.NET but it did not worked.
Dim ActiveWorkSheet As Microsoft.Office.Interop.Excel.Worksheet=
Globals.ThisWorkbook.Application.Activeworkbook.Worksheet(ActiveWorkSheet.Previous).select()
(Answer 1) You can try the following as it will store the last page into your workbook. Make sure to remove the msgbox's when you have this operating how you would like it to. I put the following code in the ThisWorkBook object in Excel.
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim docProp As DocumentProperty
Dim strSheet As String
With ThisWorkbook
If .CustomDocumentProperties.Count > 0 Then
For Each docProp In .CustomDocumentProperties
If LCase(Trim(docProp.Name)) = "previoussheet" Then
strSheet = .ActiveSheet.Name
docProp.Value = strSheet
MsgBox "Worksheet (" & strSheet & ") has been saved."
Exit For
End If
Next
Else
.CustomDocumentProperties.Add "PreviousSheet", False, msoPropertyTypeString, ThisWorkbook.ActiveSheet.Name
End If
End With
End Sub
Private Sub Workbook_Open()
Dim wrk As Workbook
Dim docProp As DocumentProperty
Dim strSheet As String
Set wrk = ThisWorkbook
If wrk.CustomDocumentProperties.Count > 0 Then
For Each docProp In wrk.CustomDocumentProperties
If LCase(Trim(docProp.Name)) = "previoussheet" Then
strSheet = docProp.Value
wrk.Worksheets(strSheet).Select
MsgBox "Worksheet " & strSheet & " has been selected."
Exit For
End If
Next
End If
Set wrk = Nothing
End Sub
(Answer 2) You can try doing this. However, you will need to open the workbook using the object below and then hold that variable (objExcel) in memory until you are done with it. The set keyword is required by vba, but if you are doing this in vb.net then, you can remove the set keywords and then you can set the object equal to nothing once you are done with it. Here is the code:
Public objExcel As Object
Dim strSheet as string
Dim intSheet as integer
Public Sub GetPrevSheet()
Dim intI as integer
Set objExcel = CreateObject("Excel.Application")
strSheet = objExcel.ActiveWorkbook.ActiveSheet.Name
'Find the sheet with the same name as the active sheet
for intI = 1 to objExcel.Activeworkbook.Worksheets.count
if lcase(trim(strsheet)) = _
lcase(trim(objExcel.ActiveWorkbook.Worksheet(inti).name)) then
intSheet = intI
exit for
End if
next intI
'Go back 1 and then select it.
if intSheet > 1 then intSheet = intSheet - 1
objExcel.Activeworkbook.Worksheets(intSheet).select
Set objExcel = Nothing
End Sub

IF statement and inputbox check validate user input

I have a code that asks the user to select a sheet by writing its name in an inputbox, and then I need to check if the selected name is correct.
How can I write the "if" statement so to return back to the inputbox?
I'm using MS Word in Windows 7. This is the code:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
Sub OpenExcelFile()
Dim oExcel As Excel.Application
Dim oWB As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim oneRange As Excel.Range
Dim aCell As Excel.Range
Dim intChoice As Integer
Dim strPath As String
Dim uiSheet As String
Set oExcel = New Excel.Application
'Select the start folder
Application.FileDialog(msoFileDialogOpen _
).InitialFileName = ActiveDocument.path
'Remove all other filters
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
'Add a custom filter
Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
"Only Excel File Allowed", "*.xl*")
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
End If
'open excel file and select sheet
Set oWB = oExcel.Workbooks.Open(strPath)
Dim strBuild As String
'set Array for user input control
Dim myArray() As Variant
ReDim myArray(1 To oWB.Sheets.Count)
'populate input box and array
For Each xlSheet In oWB.Worksheets
strBuild = strBuild & xlSheet.Name & vbCrLf
For i = 1 To oWB.Sheets.Count
myArray(i) = oWB.Sheets(i).Name
Next i
Next xlSheet
'show inputbox with list of sheets
strBuild = Left$(strBuild, Len(strBuild) - 2)
uiSheet = InputBox("Provide a sheet name." & vbNewLine & strBuild)
'check if User input match with sheet name
If IsInArray(uiSheet, myArray) Then
'show excel window
oExcel.Visible = True
'sort selected sheet by first column range
oExcel.Worksheets(uiSheet).Activate
Set oneRange = oExcel.Range("A1:A150")
Set aCell = oExcel.Range("A1")
oneRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes
Else
MsgBox "Please enter a valid name!", vbCritical
End If
End Sub
If you replace the code starting with uiSheet = InputBox(..... with the code below, it should work.
'check if User input match with sheet name
Dim bSheetPresent As Boolean
bSheetPresent = False
Do Until bSheetPresent
uiSheet = InputBox("Provide a sheet name." & vbNewLine & strBuild)
If uiSheet = "" Then Exit Do
If IsInArray(uiSheet, myArray) Then
bSheetPresent = True
Else
MsgBox "Please enter a valid name!", vbCritical
End If
Loop
If bSheetPresent Then
'show excel window
oExcel.visible = True
'sort selected sheet by first column range
oExcel.Worksheets(uiSheet).Activate
Set oneRange = oExcel.Range("A1:A150")
Set aCell = oExcel.Range("A1")
oneRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes
End If
If the user presses cancel on the inputbox, the it will exit the loop.
You may also consider to build a form with a pre-filled combobox. That way the user cannot make a mistake.
To create create your own inputbox with a list of sheets, you can do this:
Create a userform in the VBE
Name it frmSelectSheet
Put a combobox on it named cbSheets
Add the following code to the userform's code pane:
Private Sub UserForm_Initialize()
Dim oSheet As Worksheet
For Each oSheet In ThisWorkbook.Sheets
Me.cbSheets.AddItem oSheet.Name
Next oSheet
End Sub
Private Sub cbSheets_Change()
Me.Hide
End Sub
Add a module and add the following code to it:
Public Function SheetInputBox() As String
Dim ofrmSheetInput As New frmSelectSheet
ofrmSheetInput.Show
SheetInputBox = ofrmSheetInput.cbSheets
Unload ofrmSheetInput
End Function
Call the function like this
? SheetInputBox or uiSheet = SheetInputBox

VBA Code to Create Sheets based on the values in column A

I am looking for a code to create sheets with the name in column A. I have used this code but it is not fulfulling my requirement. The code is ;
Private Sub CommandButton1_Click()
Dim sheetCount As Integer
Dim sheetName As String
Dim workbookCount As Integer
With ActiveWorkbook
sheetCount = Sheets(1).Range("A2").End(xlDown).Row
For i = 2 To sheetCount Step 1
sheetName = .Sheets(1).Range("A" & i).Value
workbookCount = .Worksheets.Count
.Sheets.Add After:=Sheets(workbookCount)
.Sheets(i).Name = sheetName
'.Sheets(i).Range("A" & i, "F" & i).Value = .Sheets("sample").Range("A" & i, "F" & i).Value
Next
End With
Worksheets(1).Activate
End Sub
Upon running this code in first go, it creates sheets with the text present in column A. But the problem is when i entered new text in that column, it makes previous sheets as well. I am looking for a code which only create the sheets with the new text being entered in the column and donot make sheets which are already made. Kindly help me out on this as i tried too much but didnt find any code.
Thanks
This works for me, and is tested: Note, if you try to use a name like "History" that is reserved you will get an error. I am not aware of all the reserved names.
Private Sub CommandButton1_Click()
Dim lastRow As Long
Dim sheetName As String
Dim workbookCount As Long
Dim ws As Worksheet
Dim match As Boolean
lastRow = Sheets("Sheet1").Range("A2").End(xlDown).Row
For i = 2 To lastRow
match = False
sheetName = Sheets("Sheet1").Cells(i, 1).Text
For Each ws In ActiveWorkbook.Worksheets
If ws.Name = sheetName Then
match = True
End If
Next
If match = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = sheetName
End If
Next i
End Sub
Edit: Added Screen Shots
You can try thi function:
Function SheetExists(SheetName As String) As Boolean
Dim Test As Boolean
On Error Resume Next
Test = Sheets(SheetName).Range("A1").Select
If Test Then
SheetExists = True
Else
SheetExists = False
End If
End Function
Using the function this way:
Sub test()
If SheetExists("MySheet") Then
MsgBox "Sheet exists"
Else
MsgBox "Sheet is missing"
End If
End Sub
I usually have these two helper functions in my workbooks / personal workbook
Option Explicit
Function getSheetWithDefault(name As String, Optional wb As Excel.Workbook) As Excel.Worksheet
If wb Is Nothing Then
Set wb = ThisWorkbook
End If
If Not sheetExists(name, wb) Then
wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count)).name = name
End If
Set getSheetWithDefault = wb.Sheets(name)
End Function
Function sheetExists(name As String, Optional wb As Excel.Workbook) As Boolean
Dim sheet As Excel.Worksheet
If wb Is Nothing Then
Set wb = ThisWorkbook
End If
sheetExists = False
For Each sheet In wb.Worksheets
If sheet.name = name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function
To create the worksheets you just iterate over the sheet names and use the getSheetwithDefault function
The following code demonstrate this:
sub createSheets()
dim cursor as Range: set cursor = Sheets("Sheet1").Range("A2")
while not isEmpty(cursor)
getSheetWithDefault(name:=cursor.value)
set cursor = cursor.offset(RowOffset:=1)
wend
end

Resources