VBA to Select Each Option in a Drop List - excel

Update to code & question:
The current code in the module for this sheet is as follows:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B2:B2")) Is Nothing Then
Application.Run "MonthlyRead"
End If
End Sub
Sub MPrintAll()
Dim c As String
Dim MonthlyList As Range
Set MonthlyList = Worksheets("Monthly").Range("MonthlyList").Cells
For Each cell In MonthlyList
Range("b2").Value = cell.Value
ActiveWorkbook.Worksheets("Monthly").PrintOut
Next cell
End Sub
I've been stepping through the code, to try to identify where the problems occur. When I press F8 after "Range("b2").Value = cell.Value" it immediately goes to the first line of code for the sheet, completely skipping the Print command. Also, it deletes the first value in the named range, instead of copy-pasting it to cell B2.
For reference, here's the code in Module1 called by the first routine above:
Sub MonthlyRead()
Call MEFTPS
Call MUCT6
End Sub
Sub MEFTPS()
If Range("a2").Value = "EFTPS Package" Then
Call MShow
Else: Call MHide
End If
End Sub
Sub MHide()
Rows("20:20").Select
Selection.EntireRow.Hidden = True
Rows("31:31").Select
Selection.EntireRow.Hidden = True
Rows("42:42").Select
Selection.EntireRow.Hidden = True
Rows("53:53").Select
Selection.EntireRow.Hidden = True
Range("B2").Select
End Sub
Sub MShow()
Rows("20:20").Select
Selection.EntireRow.Hidden = False
Rows("31:31").Select
Selection.EntireRow.Hidden = False
Rows("42:42").Select
Selection.EntireRow.Hidden = False
Rows("53:53").Select
Selection.EntireRow.Hidden = False
Range("B2").Select
End Sub
Sub MUCT6()
If Range("g3").Value = "Y" Then
Call UCT6MShow
Else: Call UCT6MHide
End If
End Sub
Sub UCT6MHide()
Rows("19:19").Select
Selection.EntireRow.Hidden = True
Rows("30:30").Select
Selection.EntireRow.Hidden = True
Rows("41:41").Select
Selection.EntireRow.Hidden = True
Rows("52:52").Select
Selection.EntireRow.Hidden = True
Range("B2").Select
End Sub
Sub UCT6MShow()
Rows("19:19").Select
Selection.EntireRow.Hidden = False
Rows("30:30").Select
Selection.EntireRow.Hidden = False
Rows("41:41").Select
Selection.EntireRow.Hidden = False
Rows("52:52").Select
Selection.EntireRow.Hidden = False
Range("B2").Select
End Sub
I'm working with a dynamic worksheet that populates an individualized payment schedule, based on a selection from a data validation drop-list at the top of the page. There are approximately 300 options in the drop-list. These schedules are then printed, to verify information obtained from 2 other programs, all of which must be printed, copied, scanned, packed, and mailed in a single day.
I'm looking for VBA code that can select each client name from the drop-list in order, from the beginning to the end of the list. The list is populated from a named range on another sheet, named "QtrlyList."
I have some very simple code, that doesn't work.
Sub PrintAll()
For Each cell In QtrlyList
Worksheets("Normal").PrintOut
Next cell
End Sub
Whenever I try to run the code, I get a "Type Mismatch" error. I'm fairly certain this is coming from "cell" or "QtrlyList." I'm just not sure how to fix it.

Something like this might work for you (untested)
Sub PrintAll()
Dim wb as Workbook, cell as Range
Set Wb = ActiveWorkbook 'or ThisWorkBook if the code is in your reporting workbook
For Each cell In wb.Sheets("SheetNameHere").Range("QtrlyList").Cells
With wb.Worksheets("Normal")
'you want to set the value of whichever cell has the drop-down
.Range("D2")).value=cell.Value
DoEvents 'allow sheet to pick up changed value
.PrintOut
End with
Next cell
End Sub

Related

Why does the Range method Select work the first time but not the second

Sub History1()
'
' History Macro
'
'
Dim sDate As String
Application.ScreenUpdating = False
sDate = Sheets("Summary").Range("P1").Value
If Not WorksheetExists(sDate) Then
Sheets.Add.Name = sDate
End If
Sheets(sDate).Visible = True
Sheets(sDate).Cells.UnMerge
Sheets("Summary").Range("A1:Z100").Select
Selection.Copy
Sheets(sDate).Range("A1:Z100").Select
Selection.Paste
Sheets(sDate).Visible = False
Sheets("Summary").Cells(3, 1).Select
Application.ScreenUpdating = True
' MsgBox ("Done")
End Sub
The value in sDate is the string 05_14_21 and works fine when used earlier in the sub. The first instance of Range.Select operation works fine, at least I think it does. No error generated. The second one says "Select method of Range class failed". The worksheet "05_14_21" is visible at the time of the 2nd operation. I am at a loss. Any insights will be appreciated.Th
You cant use .Select on a range of a sheet that isn't active. It will give you Run-Time Error 1004. The fix would be to first select that sheet, then select the range. But honestly, using .Select is unnecessary and will make the screen jitter around while the macro is running. .Select also slows down your macro, which becomes very noticeable when you start using loops in your code.
Instead I would suggest directly referencing your ranges instead of using .Select like so:
Sub History1()
Dim sDate As String
Application.ScreenUpdating = False
sDate = Sheets("Summary").Range("P1").Value
If Not WorksheetExists(sDate) Then
Sheets.Add.Name = sDate
End If
Sheets(sDate).Visible = True
Sheets(sDate).Cells.UnMerge
Sheets("Summary").Range("A1:Z100").Copy Destination:= Sheets(sDate).Range("A1:Z100")
Sheets(sDate).Visible = False
Application.ScreenUpdating = True
' MsgBox ("Done")
End Sub
I am not sure why you need to select Cells(3,1), but in order to do that you need to activate the correct sheet. As pointed out in another answer, using select is not advisable. This also results in a more concise way to copy and paste.
Dim sDate As String
Application.ScreenUpdating = False
sDate = Sheets("Summary").Range("A1").Value
If WorksheetExists(sDate) = False Then
Sheets.Add.Name = sDate
End If
Sheets(sDate).Visible = True
Sheets(sDate).Cells.UnMerge
Sheets("Summary").Range("A1:Z100").Copy _
Destination:=Sheets(sDate).Range("A1:Z100")
Sheets(sDate).Visible = False
Sheets("summary").Activate
Sheets("Summary").Cells(3, 1).Select
Application.ScreenUpdating = True

Pause VBA Script While Links Update

This is my second post about this macro. Although the first post received a few responses, none of the responses solved the problem (thank you for responding though).
Scenario:
I have about 20 sub-spreadsheets with links to external sources. The number of links per spreadsheet varies from about 500 to 10,000. A master spreadsheet calls macros to open each sub-spreadsheet in turn and update the links.
Each sub-spreadsheet has a dashboard that tells me how many links remain to be updated. This is done by counting the number of “N/A” values in each tab, then summing these counts in cell A20. As the links are updated, the value in A20 counts down to zero.
Sub Sub01()
Dim NAtotal As Integer
Set ActiveWKB = Workbooks.Open("Sub01.xlsm")
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
Application.CalculateFull
ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
NAtotal = Worksheets("Dashboard").Cells(20, "C").Value
MsgBox (NAtotal) 'Tells me how many cells remain to be updated – starts off at 4450.
NAtotal = 100 'Debugging effort to let me know that NAtotal does adjust.
MsgBox (NAtotal)
Do Until NAtotal = 0
Application.ScreenUpdating = True
MsgBox (NAtotal) 'Another debugging effort to monitor NAtotal. Starts at 100, then jumps to (and remains at) 4450 on the second loop and all subsequent loops.
NAtotal = Worksheets("Dashboard").Cells(20, "C").Value 'Resets NAtotal to the value in C20. This never changes, but remains at 4450.
DoEvents
Loop
Application.Calculation = xlManual
MsgBox ("Done")
Sheets("Dashboard").Activate
Range("B1").Select
ActiveWorkbook.Save
ActiveWindow.Close
End Sub`
The macro should continue to loop until cell A20 hits zero, and then stop.
Cell A20 does count down, but variable NAtotal remains at its initial value.
Any guidance/recommendations are appreciated.
Hi the code below worked for me. Try use the same method instead of using a loop. The schedule will trigger every second until the NATotal = 0 logically anyway. Just update the code to fit your references.
Public firstOpen As Boolean
Sub testForm()
Dim cellCount As Integer
Dim s1 As Sheet1
Set s1 = Sheet1
Dim cellCol As Integer
Dim activeWbk As Workbook
Dim ws As Worksheet
If firstOpen = False Then
firstOpen = True
Set activeWbk = Workbooks.Open("C:\Example\Link2.xlsm")
Set ws = activeWbk.Sheets("Sheet1")
Application.Calculation = xlCalculationAutomatic
Application.CalculateFull
activeWbk.UpdateLink Name:=ActiveWorkbook.LinkSources
CreateNewSchedule
Exit Sub
Else
Set activeWbk = Workbooks("Link2.xlsm")
Set ws = activeWbk.Worksheets("Sheet1")
End If
cellCount = ws.Range("N2").Value
If cellCount = 0 Then
MsgBox ("Done...")
Application.Calculation = xlCalculationManual
firstOpen = false
Else
Debug.Print cellCount
CreateNewSchedule
End If
'Application.Calculation = xlCalculationManual
End Sub
Sub CreateNewSchedule()
Application.OnTime Now + TimeValue("00:00:01"), Procedure:="testForm", Schedule:=True
End Sub

Form Control Checkbox to Copy and Paste Text from a Different Sheet

I am looking for a way to copy and paste text from one sheet to another when I tick a form control checkbox and to delete it when I uncheck it. At the moment the macro I have written does nothing, it doesn't come up with any errors it just doesn't work. What I have so far is:
Sub CheckBox3_Click()
Application.ScreenUpdating = False
If CheckBox3 = True Then
Sheets("Data Sheet").Activate
Range("B1").Select
Selection.Copy
Sheets("Sheet1").Select
Range("C1").Select
ActiveSheet.Paste
Application.ScreenUpdating = True
End If
If CheckBox3 = False Then
ActiveSheet.Range("C1").Select
Selection.Delete
End If
End Sub
Any help would be appreciated, thanks.
To overcome your Runtime error please change your code to
ActiveSheet.Range("B1").Select
and do the same for the target range C1
However, the much more elegant way is to get rid of Select and Activate all together by using VBA rather than "macro recording" ... work with Range objects which will simplify your code, you avoid messy screen jumps etc ...
Private Sub CheckBox1_Click()
Dim SrcRange As Range, TrgRange As Range
Set SrcRange = Worksheets("Data Sheet").[B1]
Set TrgRange = Worksheets("Sheet1").[C1]
If CheckBox1 Then
TrgRange = SrcRange
Else
TrgRange = ""
End If
End Sub

hide rows excel vba does not work when not triggered

I have a macro that works perfectly well when triggered on an onchange event. It simply checks a cell value and hides or unhides rows elsewhere on the same active sheet. Here is the macro that hides or unhides rows:
Sub ToggleTaskTable()
MsgBox "Toggling Tasks"
If Cells(56, 3).Value = "No" Then
Cells(57, 1).EntireRow.Hidden =
MsgBox "Hding Rows 106, 148 and 190"
ActiveSheet.Rows("106").Hidden = True
ActiveSheet.Rows("148").Hidden = True
ActiveSheet.Rows("190").Hidden = True
' try it another way
Rows("106").Hidden = True
Rows("148").Hidden = True
Rows("190").Hidden = True
Else
Cells(57, 1).EntireRow.Hidden = False
' MsgBox "Showing task Rows 106, 148 and 190"
Rows("106").Hidden = False
Rows("148").Hidden = False
Rows("190").Hidden = False
End If
End Sub
If I call the macro as a result of changing a cell C56 to "No", it works perfectly.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$C$56" Then
Call ToggleTaskTable
End If
End Sub
If I call the macro from another macro, with C56 set to "No", it does not work at all.
Sub CallAllMacros()
Call ToggleTaskTable
End Sub
Even though the msgbox shows indicating it is hiding the rows, it does not actually hide them.
I am totally stumped!
Sub ToggleTaskTable()
With ActiveSheet
.Range("A57,A106,A148,A190").EntireRow.Hidden = (.Cells(56, 3).Value = "No")
End With
End Sub

How to Freeze sheets in Excel

I am facing a problem in my excel workbook. I have 25+ sheets in my workbook
and I want to look to sheet1 time to time. Is their any way that I can freeze first
two sheets of my workbook?
Currently I am navigating through sheets by pressing ctrl+page up button.
FYI I am Using MS-Office 2007
If I have understood well: you want the users stay only on Sheet1 & 2:
In the Main event:
Private Sub Workbook_Open()
ActiveWindow.DisplayWorkbookTabs = False
End Sub
and in the Event:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If ActiveWindow.DisplayWorkbookTabs Then ActiveWindow.DisplayWorkbookTabs = False
If ((Sh.Name) <> "Sheet1") And ((Sh.Name) <> "Sheet2") Then Sheets("Sheet1").Select
End Sub
When open disable Tabs. If people show if you try to change the code return to Sheet1.
Ad Password to VBA macro ...If is only for quick change remove the code of Tabs...
This code (in the ThisWorkbook module) will keep Sheet1 just to the left of whatever sheet you're on.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Application.EnableEvents = False
If Sh.Name <> Sheet1.Name Then
Sheet1.Move Sh
Sh.Activate
End If
Application.EnableEvents = True
End Sub
It's a little weird pressing Ctrl+PgUp to navigate a bunch of sheets because it now takes two Ctrl+PgUps to move one sheet - one moves you onto Sheet1 (because it's always to the left) and the second moves you to the next sheet (which then moves Sheet1 to the left of it).
Maybe you could build in a timer so it only moves sheet1 if you've been on a sheet for a couple of seconds.
Update Using a timer
In a standard module:
Public gshToMove As Object
Public gdtTimeToMove As Date
Sub MoveSheet()
Application.EnableEvents = False
Sheet1.Move gshToMove
gshToMove.Activate
Set gshToMove = Nothing
gdtTimeToMove = 0
Application.EnableEvents = True
End Sub
In the ThisWorkbook module
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name <> Sheet1.Name Then
'if something's schedule, unschedule it
If gdtTimeToMove <> 0 Then
Application.OnTime gdtTimeToMove, "MoveSheet", , False
End If
'schedule the sheet move for three seconds from now
gdtTimeToMove = Now + TimeSerial(0, 0, 3)
Set gshToMove = Sh
Application.OnTime gdtTimeToMove, "MoveSheet", , True
End If
Application.EnableEvents = True
End Sub
You still get a little flash when the code actually runs.
In each sheet
Private Sub Worksheet_Activate ( )
Call Funciona
End Sub
In Module
Sub Funciona()
With ActiveSheet
If .Index > 1 Then
If .Previous.Name <> "Principal" Then
Sheets("Principal").Move Before:=ActiveSheet
End If
End If
End With
End Sub

Resources