I have the following code to customize the right click menu:
Sub CreateMenuItem()
Dim MenuButton As CommandBarButton
With CommandBars("Text") 'Text, Lists and Tables
Set MenuButton = .Controls.Add(msoControlButton)
With MenuButton
.Caption = "Correct"
.Style = msoButtonCaption
.OnAction = "InsertCorrect"
End With
End With
End Sub
It works fine with text and lists, but only partially with tables:
With CommandBars("Tables")
I must select the whole table or a column then it works but not inside a cell. What is the name for the context menu inside a cell or for text inside a table cell?
I made this routine to see al the names of the CommandBars in Word:
Sub ListYourCommandBars()
For Each c In CommandBars
Debug.Print c.Name
Next
End Sub
Good news they are already sorted alphabetically. I found one called Table Cells. I tried it:
With CommandBars("Table Cells")
and it worked. Only thing, a cell or a number of cells must be "wholly selected". That is, the menu-item doesnt show up if you just enter inside the cell, you must select the cell "as a whole" (dunno how to say it better). Hope this helps.
I got it to work inside a table cell by adding the MenuButton to the following Built-In CommandBars: "Text", "Linked Text", "Table Text", "Font Paragraph", "Linked Headings", "Linked Table", "Linked Text", "Lists", "Table Cells", "Table Lists", "Tables", "Tables and Borders", and "Text Box".
I’m not sure which one actually did the trick. Here’s my code:
Private DisableEvents As Boolean
Private Sub UpdateRightClickMenus()
Dim MenuButton As CommandBarButton
Dim CommandBarTypes(100) As String
Dim i As Long
Dim PRChecklistIsSelected As Boolean
Dim CheckListTypeFound As Boolean
PRChecklist = True
ResetRightClickMenus
CommandBarTypes(0) = "Text"
CommandBarTypes(1) = "Linked Text"
CommandBarTypes(2) = "Table Text"
CommandBarTypes(3) = "Font Paragraph"
CommandBarTypes(4) = "Linked Headings"
CommandBarTypes(5) = "Linked Table"
CommandBarTypes(6) = "Linked Text"
CommandBarTypes(7) = "Lists"
CommandBarTypes(8) = "Table Cells"
CommandBarTypes(9) = "Table Lists"
CommandBarTypes(10) = "Tables"
CommandBarTypes(11) = "Tables and Borders"
CommandBarTypes(12) = "Text Box"
Dim cc As ContentControl
Set cc = FindContentControlByTag("ListBox_PR_TR")
If IsNull(cc) Then
DisableEvents = False
Exit Sub
End If
'Find Selected
For i = 1 To cc.DropdownListEntries.Count
If cc.Range.Text = "Product Review" Then
PRChecklistIsSelected = True
CheckListTypeFound = True
Exit For
End If
If cc.Range.Text = "Technical Review" Then
PRChecklistIsSelected = False
CheckListTypeFound = True
Exit For
End If
Next i
If CheckListTypeFound = False Then Exit Sub
For i = 0 To 12
With Application
If PRChecklistIsSelected Then
'Add right-click menu option to set as a Product Review comment
With .CommandBars(CommandBarTypes(i))
Set MenuButton = .Controls.Add(msoControlButton)
With MenuButton
.Caption = "Set as Product Review Comment"
.Style = msoButtonCaption
.OnAction = "Set_as_Product_Review_Comment"
End With
End With
Else
'Add right-click menu option to set as a Tech Review comment
With .CommandBars(CommandBarTypes(i))
Set MenuButton = .Controls.Add(msoControlButton)
With MenuButton
.Caption = "Set as Tech Review Comment"
.Style = msoButtonCaption
.OnAction = "Set_as_Tech_Review_Comment"
End With
End With
End If
End With
Next i
RightClickMenuItemsAdded = True
End Sub
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
If DisableEvents = True Then Exit Sub
Set cc = FindContentControlByTag("ListBox_PR_TR")
If IsNull(cc) Then
ResetRightClickMenus
DisableEvents = False
Exit Sub
End If
If cc.Range.Text = "Technical Review" Then
Find_PR_Style_ReplaceWith_TR_Style
End If
UpdateRightClickMenus
DisableEvents = False
End Sub
Private Sub Find_PR_Style_ReplaceWith_TR_Style()
Set StylePR = ThisDocument.Styles("Product Review Style")
Set StyleTR = ThisDocument.Styles("Technical Review Style")
With ThisDocument.Content.Find
.ClearFormatting
.Style = StylePR
With .Replacement
.ClearFormatting
.Style = StyleTR
End With
.Execute Forward:=True, Replace:=wdReplaceAll, FindText:="", ReplaceWith:=""
End With
End Sub
Private Sub Set_as_Tech_Review_Comment()
Set StyleTR = ThisDocument.Styles("Technical Review Style")
With ThisDocument
Selection.Style = StyleTR
SetCanContinuePreviousList
End With
End Sub
Private Sub Set_as_Product_Review_Comment()
Set StylePR = ThisDocument.Styles("Product Review Style")
With ThisDocument
Selection.Style = StylePR
SetCanContinuePreviousList
End With
End Sub
Private Sub SetCanContinuePreviousList()
Dim lfTemp As ListFormat
Dim intContinue As Integer
Dim oldListNumber As Single
Set lfTemp = Selection.Range.ListFormat
oldListNumber = lfTemp.ListValue
If Not (lfTemp.ListTemplate Is Nothing) Then
intContinue = lfTemp.CanContinuePreviousList( _
ListTemplate:=lfTemp.ListTemplate)
lfTemp.ApplyListTemplate _
ListTemplate:=lfTemp.ListTemplate, _
ContinuePreviousList:=False, _
ApplyTo:=wdListApplyToWholeList
If lfTemp.ListValue = oldListNumber Then
lfTemp.ApplyListTemplate _
ListTemplate:=lfTemp.ListTemplate, _
ContinuePreviousList:=True, _
ApplyTo:=wdListApplyToWholeList
End If
End If
Set lfTemp = Nothing
End Sub
Private Function FindContentControlByTag(Tag As String) As ContentControl
For Each cc In ThisDocument.ContentControls
If cc.Tag = Tag Then
Set FindContentControlByTag = cc
Exit Function
End If
Next
End Function
Private Sub ResetRightClickMenus()
Dim CommandBarTypes(100) As String
Dim i As Long
CommandBarTypes(0) = "Text"
CommandBarTypes(1) = "Linked Text"
CommandBarTypes(2) = "Table Text"
CommandBarTypes(3) = "Font Paragraph"
CommandBarTypes(4) = "Linked Headings"
CommandBarTypes(5) = "Linked Table"
CommandBarTypes(6) = "Linked Text"
CommandBarTypes(7) = "Lists"
CommandBarTypes(8) = "Table Cells"
CommandBarTypes(9) = "Table Lists"
CommandBarTypes(10) = "Tables"
CommandBarTypes(11) = "Tables and Borders"
CommandBarTypes(12) = "Text Box"
For i = 0 To 12
Application.CommandBars(CommandBarTypes(i)).Reset
Next i
RightClickMenuItemsAdded = False
End Sub
Private Sub Document_Open()
UpdateRightClickMenus
End Sub
Private Sub Document_Close()
ResetRightClickMenus
End Sub
Related
This is my first ever question on SO even I come here regularly (I've always find my answer without having to ask until today). I know this question I've already posted but for some reason i doesn't work for me.
I'm trying to get a right click submenu with a list of every numbered items in my word document. The purpose of it is to insert in a click the numbered and the content text of my numbered item in my document.
The problem is I don't know how to affect each .OnAction (to insert the numbered item in my document) and each .Caption (to show the number and content text of my numbered item in my menu) with a different variable (one for each numbered item). There is probably a problem with my quotes but I cannot see any other solution.
My code is the following :
Option Explicit
Sub ControlButtonNumberedItems()
'Parameters for NumberedItems
Dim i As Integer
i = 1
Dim NumberedItems As Integer
NumberedItems = ActiveDocument.CountNumberedItems
'Parameters for CommanBar
Dim MenuButton As CommandBar
Set MenuButton = Application.CommandBars("Text")
Dim SubMenuButton As CommandBarControl
Set SubMenuButton = MenuButton.Controls.Add(Type:=msoControlPopup, Before:=1)
With SubMenuButton
.Caption = "NumberedItems"
.Tag = "My_Tag"
While i <= NumberedItems
With .Controls.Add(Type:=msoControlButton)
.OnAction = "'InsertNumberedItem""i""'"
.FaceId = 38
.Caption = "MyCaption"
End With
i = i + 1
Wend
End With
End Sub
Sub InsertEvidence(i As Integer)
'Insert NumberRelativeContext
Selection.InsertCrossReference ReferenceType:=wdRefTypeNumberedItem, _
ReferenceKind:=wdNumberRelativeContext, _
ReferenceItem:=i, _
InsertAsHyperlink:=True, _
SeparatorString:=" "
Selection.TypeText Text:=" "
'Insert ContentText
Selection.InsertCrossReference ReferenceType:=wdRefTypeNumberedItem, _
ReferenceKind:=wdContentText, _
ReferenceItem:=i, _
InsertAsHyperlink:=True, _
SeparatorString:=" "
'Text form
Selection.Expand Unit:=wdLine
Selection.Font.Bold = wdToggle
Selection.Font.Italic = wdToggle
Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
Selection.ParagraphFormat.SpaceBefore = 6
End Sub
Sub ResetRightClick()
Application.CommandBars("Text").Reset
End Sub
Thank you in advance for any help. Please let me know if you need any other information.
I didn't know that Word VBA is different from Excel: see the accepted answer here:
VBA Pass arguments with .onAction
This worked for me (just the code needed to show how parameters can be passed):
Sub ControlButtonNumberedItems()
Dim i As Integer
Dim NumberedItems As Integer
'Parameters for CommanBar
Dim MenuButton As CommandBar
Set MenuButton = Application.CommandBars("Text")
Dim SubMenuButton As CommandBarControl
Set SubMenuButton = MenuButton.Controls.Add(Type:=msoControlPopup, Before:=1)
With SubMenuButton
.Caption = "NumberedItems"
.Tag = "My_Tag"
For i = 1 To 5
With .Controls.Add(Type:=msoControlButton)
.OnAction = "InsertNumberedItem"
.FaceId = 38
.Parameter = i
.Caption = "MyCaption " & i
End With
Next i
End With
End Sub
Public Sub InsertNumberedItem()
MsgBox "got " & CommandBars.ActionControl.Parameter
End Sub
Sub ResetRightClick()
Application.CommandBars("Text").Reset
End Sub
I am having an issue regarding VBA in Word 2013. I have limited experience with coding, and macros are a bit of new territory for me.
I have a successful VBA code from a worker that no longer works in my office, and this code allows for a drop down menu in the office forms, allowing the user to choose their location and the footer changes the text address of the office in a string.
What I have been trying to do is to tweak this code so that on choosing the location, instead of showing text at the bottom of the page, the header template will change. I have successfully recorded the macros so it will do what I want on my computer, but when I try to share it with others, a few things happen. The drop down menu doesn't appear, then I have to put in the Developer tab. After that I have to unlock the document each time I want to run the macro (the old documents did not require this even though the old documents are also locked), then I get the error code saying the requested member does not exist, pointing to my recorded macro.
I'm sure I am doing something wrong but I'm unsure what that is. Some help would be greatly appreciated.
Option Explicit
Sub AutoNew()
Dim Mybar As CommandBar
Dim myControl As CommandBarComboBox
Dim cmd As CommandBar
Dim cmdyes As Integer
cmdyes = 0
For Each cmd In CommandBars
If cmd.Name = "Select Location" Then
cmdyes = 1
Exit For
Else
End If
Next
If cmdyes = 1 Then
CommandBars("Select Location").Visible = True
Else
Set Mybar = CommandBars _
.Add(Name:="Select Location", Position:=msoBarFloating, _
Temporary:=False)
Set myControl = CommandBars("Select Location").Controls _
.Add(Type:=msoControlDropdown, Before:=1)
With myControl
.AddItem " South Portland"
.AddItem " Bangor"
.AddItem " Presque Isle"
.ListIndex = 1
.Caption = "Select Office Location"
.Style = msoComboLabel
.BeginGroup = True
.OnAction = "processSelection"
.Tag = "AddresSelect"
End With
End If
CommandBars("Select Location").Visible = True
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields = False Then
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True,
Password:="password"
' ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True,
Password:=""
End If
End Sub
Sub AutoOpen()
Dim Mybar As CommandBar
Dim myControl As CommandBarComboBox
Dim cmd As CommandBar
Dim cmdyes As Integer
cmdyes = 0
For Each cmd In CommandBars
If cmd.Name = "Select Location" Then
cmdyes = 1
Exit For
Else
End If
Next
If cmdyes = 1 Then
CommandBars("Select Location").Visible = True
Else
Set Mybar = CommandBars _
.Add(Name:="Select Location", Position:=msoBarFloating, _
Temporary:=False)
Set myControl = CommandBars("Select Location").Controls _
.Add(Type:=msoControlDropdown, Before:=1)
With myControl
.AddItem " South Portland"
.AddItem " Bangor"
.AddItem " Presque Isle"
.ListIndex = 1
.Caption = "Select Office Location"
.Style = msoComboLabel
.BeginGroup = True
.OnAction = "processSelection"
.Tag = "AddresSelect"
End With
End If
CommandBars("Select Location").Visible = True
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields = False Then
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True,
Password:="password"
' ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True,
Password:=""
End If
End Sub
Sub processSelection()
Dim userChoice As Long
userChoice = CommandBars("Select Location").Controls(1).ListIndex
Select Case userChoice
Case 1
Call SoPortlandAddress
Case 2
Call BangorAddress
Case Else
Call PresqueIsleAddress
End Select
End Sub
Sub SoPortlandAddress()
'
' SoPortlandAddress Macro
'
'
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Templates.LoadBuildingBlocks
Application.Templates( _
"C:\Users\bex172\AppData\Roaming\Microsoft\Document Building
Blocks\1033\15\Building Blocks.dotx" _
).BuildingBlockEntries("South Portland Header").Insert Where:=Selection.
_
Range, RichText:=True
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
ActiveDocument.Unprotect Password:="password"
End If
If ActiveDocument.ProtectionType = wdNoProtection Then
FormLock
End If
End Sub
Sub BangorAddress()
'
' BangorAddress Macro
'
'
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Templates.LoadBuildingBlocks
Application.Templates( _
"C:\Users\bex172\AppData\Roaming\Microsoft\Document Building
Blocks\1033\15\Building Blocks.dotx" _
).BuildingBlockEntries("Bangor Header").Insert Where:=Selection.Range, _
RichText:=True
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
ActiveDocument.Unprotect Password:="password"
End If
If ActiveDocument.ProtectionType = wdNoProtection Then
FormLock
End If
End Sub
Sub PresqueIsleAddress()
'
' PresqueIsleAddress Macro
'
'
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
Templates.LoadBuildingBlocks
Application.Templates( _
"C:\Users\bex172\AppData\Roaming\Microsoft\Document Building
Blocks\1033\15\Building Blocks.dotx" _
).BuildingBlockEntries("Presque Isle Header").Insert Where:=Selection. _
Range, RichText:=True
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields Then
ActiveDocument.Unprotect Password:="password"
End If
If ActiveDocument.ProtectionType = wdNoProtection Then
FormLock
End If
End Sub
Sub FormLock()
'
' ToggleFormLock Macro
' Macro created 1/27/2004 by name removed
'
If ActiveDocument.ProtectionType = wdAllowOnlyFormFields = False Then
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True,
Password:="password"
'if a password is used, add the line below after a space above
'Password:="myPassword"
Else
'if a password is used, add a comma after
'the last line and include the line below
'Password:="myPassword"
End If
End Sub
I found your code a little unwieldy and understand that it poses a problem for you. The abbreviated version below should be easier to understand and therefore easier for you to manage once you acquaint yourself with its own peculiarities. Note that I tested everything except the actual extraction and insertion of the building block, since you said it is working.
Option Explicit
' declare the name (so as to eliminate typos)
Const CmdName As String = "Select Location"
Sub AutoNew()
' 12 Oct 2017
SetCommandBar
End Sub
Sub AutoOpen()
' 12 Oct 2017
SetCommandBar
End Sub
Sub SetCommandBar()
' 12 Oct 2017
Dim MyBar As CommandBar
Dim MyCtl As CommandBarControl
Dim MyList() As String
Dim Cmd As CommandBar
Dim i As Integer
' delete the existing (so that you can modify it)
For Each Cmd In CommandBars
If Cmd.Name = CmdName Then
Cmd.Delete
Exit For
End If
Next Cmd
' in Word >= 2007 the commandbar will be displayed
' in the ribbon's Add-ins tab
Set MyBar = CommandBars.Add(Name:=CmdName, _
Position:=msoBarFloating, _
MenuBar:=True, _
Temporary:=True)
Set MyCtl = CommandBars(CmdName).Controls.Add( _
Type:=msoControlDropdown, _
Before:=1)
' Names must match Building Block names (without " Header")
MyList = Split(" South Portland, Bangor, Presque Isle", ",")
With MyCtl
.Caption = "Select Office Location"
.Style = msoComboLabel
For i = 0 To UBound(MyList)
.AddItem MyList(i)
Next i
.ListIndex = 1
.OnAction = "SetHeader"
End With
CommandBars(CmdName).Visible = True
End Sub
Sub SetHeader()
' 12 Oct 2017
Const BlockFile As String = "C:\Users\bex172\AppData\Roaming\Microsoft\" & _
"Document Building Blocks\1033\15\" & _
"Building Blocks.dotx"
Dim BlockID As String
SetFormLock False ' not needed if the document isn't locked
With ActiveWindow
If .View.SplitSpecial <> wdPaneNone Then .Panes(2).Close
With .ActivePane.View
If .Type = wdNormalView Or .Type = wdOutlineView Then
.Type = wdPrintView
End If
.SeekView = wdSeekCurrentPageHeader
End With
End With
BlockID = Trim(CommandBars(CmdName).Controls(1).Text) & " Header"
Templates.LoadBuildingBlocks
Application.Templates(BlockFile).BuildingBlockEntries(BlockID).Insert _
Where:=Selection.Range, _
RichText:=True
SetFormLock True ' not needed if the document isn't to be locked
End Sub
Sub SetFormLock(ByVal FormLock As Boolean)
' 12 Oct 2017
' call this procedure with either "True" or "False" as argument
' to either lock or unlock the form.
' The same password is used for unlocking and locking.
' MAKE SURE THE DOCUMENT IS UNLOCKED before changing the password!
Const Password As String = ""
Dim Doc As Document
Set Doc = ActiveDocument
With Doc
If .ProtectionType = wdNoProtection Then
If FormLock Then
' you can't set the protection while any other part of the document is active
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
' you may wish to specify another type of protection:
' this code protects all except FormFields
.Protect Type:=WdProtectionType.wdAllowOnlyFormFields, _
NoReset:=True, _
Password:=Password, _
UseIRM:=False, _
EnforceStyleLock:=False
End If
Else
If Not FormLock Then .Unprotect Password
End If
End With
End Sub
Your question didn't allow full understanding of your problem. It might have to do with the location of the code itself or with the protection. By making the code more transparent I hope that you will either be able to eliminate the problem or find the right question to ask.
I'm Using Excel 2013 vba. I have 2 Forms: frmMain and . In frmMain, I only have a cmd button with a code UserForm1.show ,however i can't open the UserForm1.
Here's my code:
Private Sub Workbook_Open()
Application.Visible = False 'This code hides the workbook
UserForm1.Show 'Brings the UserForm
End Sub
'Module1 Code..
Sub hidden()
Sheet1.Visible = False
End Sub
screenshot of my UserForm1
Code for UserForm1...
'Application.ScreenUpdating = False
'Sheets("Sheet1").Visible = True
Private Sub cmbCalltype_Change()
'==========sayon rani dri=======
'If cmbCalltype.List(cmbCalltype.ListIndex) = "Training" Then
' cmbGc.Enabled = False
'ElseIf cmbCalltype.List(cmbCalltype.ListIndex) = "Wrong GC" Then
' cmbGc.Enabled = False
'ElseIf cmbCalltype.List(cmbCalltype.ListIndex) = "Wrong Number" Then
' cmbGc.Enabled = False
'ElseIf cmbCalltype.List(cmbCalltype.ListIndex) = "Resident" Then
' cmbGc.Enabled = False
'Else
' cmbGc.Enabled = True
'End If
If cmbCalltype.Text = "Training" Then
cmbGc.Enabled = False
ElseIf cmbCalltype.Text = "Resident" Then
cmbGc.Enabled = False
ElseIf cmbCalltype.Text = "Wrong GC" Then
cmbGc.Enabled = False
ElseIf cmbCalltype.Text = "Wrong Number" Then
cmbGc.Enabled = False
Else
cmbGc.Enabled = True
End If
End Sub
Private Sub cmdApplicationshow_Click()
Application.Visible = True 'This will open the excel file...
End Sub
Private Sub cmdClear_Click()
'==========sayon rani dri=======
'Call UserForm_Initialize
txtName.Value = ""
cmbCalltype.Value = ""
cmbGc.Value = ""
cmbVisit.Value = ""
End Sub
Private Sub cmdHidden_Click()
Application.Visible = False 'This will open the excel file...
End Sub
Private Sub cmdMove_Click()
'Dim emptyRow As Long
'Sheet1.Activate 'Make Sheet1 active
'emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
'Transfer information
'Cells(emptyRow, 1).Value = txtName.Value
'Cells(emptyRow, 2).Value = cmbCalltype.Value
'Cells(emptyRow, 3).Value = cmbVisit.Value
With Sheet1
With .Range("A" & .Rows.Count).End(xlUp)
.Offset(1).Resize(1, 4).Value = Array(txtName.Value, cmbCalltype.Value, cmbGc.Value, cmbVisit.Value)
End With
txtLeasing.Value = Application.CountIf(.Columns(2), "Leasing") 'counting the number of instances leasing text occur
txtGc.Value = Application.CountIf(.Columns(3), "Yes")
'txtYes.Value = Application.CountIf(.Columns(4), "Yes")
'txtNo.Value = Application.CountIf(.Columns(4), "No")
txtPercentage.Value = txtGc.Value / txtLeasing.Value * 100
''==================
txtVisLeasing.Value = txtLeasing.Value
txtTotvisit.Value = Application.CountIf(.Columns(4), "Yes")
txtVisitper.Value = txtTotvisit.Value / txtVisLeasing * 100
End With
End Sub
Private Sub UserForm_Initialize()
'Worksheets("Sheet1").Activate
'Sheets("Sheet1").Visible = False
txtName.Value = "" 'Empty Customer
cmbCalltype.Value = "" 'Empty Call Type
cmbGc.Value = "" 'Empty GC
cmbVisit.Value = "" 'Empty Visit
cmbCalltype.Clear
With cmbCalltype
.AddItem "Leasing"
.AddItem "Training"
.AddItem "Resident"
.AddItem "Wrong GC"
.AddItem "Wrong Number"
End With
cmbGc.Clear
With cmbGc
.AddItem "Yes"
.AddItem "No"
End With
cmbVisit.Clear
With cmbVisit
.AddItem "Yes"
.AddItem "No"
End With
txtName.SetFocus
End Sub
Is the instance of UserForm1 called from Workbook_Open() same as the instance of UserForm1 called from frmMain ?
If Yes, then create a Module and declare the instance of UserForm1 in Module1 as Public.
If No, then declare a form level instance of UserForm1 in frmMain.
Something like below.
'frmMain Code
Dim fUser As UserForm1
Private Sub CommandButton1_Click()
If fUser Is Nothing Then
fUser = New UserForm1
End If
fUser.Show
End Sub
I need to open a dialog box and select a workbook. Then copy the data placed in that workbook (which has only 1 sheet with same name all the time).
I want to do the process for many workbooks by using a loop for vbyesno.
This is the only part which is not working because I want to paste data under Range("a14"), then loop and then paste under the data pasted in a14.
Below is the macro which is being called from another macro.
Sub prompt()
Application.DisplayAlerts = False
Dim Target_Workbook As Workbook
Dim Source_Workbook As Workbook
Dim Target_Path As Range
d = MsgBox("Add record?", vbYesNoCancel + vbInformation)
If d = vbNo Then
ActiveSheet.Range("a13").value = "No data Found"
ActiveSheet.Range("a13").Font.Bold = True
ThisWorkbook.Save
ElseIf d = vbCancel Then
Sheets("MPSA").Delete
ThisWorkbook.Save
ElseIf d = vbYes Then
Sheets("MPSA").Range("a14").value = "NAME"
Sheets("MPSA").Range("b14").value = "NUMBER"
Sheets("MPSA").Range("c14").value = "AGR NUMBER"
Sheets("MPSA").Range("d14").value = "ENTITY NAME"
Sheets("MPSA").Range("e14").value = "GROUP"
Sheets("MPSA").Range("f14").value = "DELIVERABLE"
Sheets("MPSA").Range("g14").value = "DELIVERAB"
Sheets("MPSA").Range("h14").value = "IS COMPON"
Sheets("MPSA").Range("i14").value = "PACKAGE"
Sheets("MPSA").Range("j14").value = "ORDERS"
Sheets("MPSA").Range("k14").value = "LICNTITY"
Sheets("MPSA").Range("l14").value = "QUANTITY"
Sheets("MPSA").Range("m14").value = "ORDERANUMBER"
Sheets("MPSA").Range("n14").value = "ORDERAM NAME"
Sheets("MPSA").Range("o14").value = "PAC NUMBER"
Sheets("MPSA").Range("p14").value = "PACKAGAME"
Sheets("MPSA").Range("q14").value = "ITTION"
Sheets("MPSA").Range("r14").value = "LICENSE TYPE"
Sheets("MPSA").Range("s14").value = "ITEM VERSION"
Sheets("MPSA").Range("t14").value = "REAGE"
Sheets("MPSA").Range("u14").value = "CLIIT"
Sheets("MPSA").Range("v14").value = "LICEAME"
Sheets("MPSA").Range("w14").value = "ASSATE"
Sheets("MPSA").Range("x14").value = "ASSTE"
Sheets("MPSA").Range("y14").value = "ENTITTUS"
Sheets("MPSA").Range("z14").value = "ASSGORY"
Sheets("MPSA").Range("aa14").value = "PURCHAYPE"
Sheets("MPSA").Range("ab14").value = "BILLTHOD"
Sheets("MPSA").Range("ac14").value = "SALETER"
Cells.Columns.AutoFit
Target_Path = Application.GetOpenFilename
Set Target_Workbook = Workbooks.Open(Target_Path)
Set Source_Workbook = ThisWorkbook
Target_Data = Target_Workbook.Sheets(1).Range("A1").CurrentRegion.Copy
Target_Workbook.Close
Source_Workbook.Sheets("MPSA").Range("a14").End(xlDown).Offset(1, 0).PasteSpecial = Target_Data
ActiveCell.EntireRow.Delete
ThisWorkbook.Save
ThisWorkbook.Save
End If
End Sub
I was going to propose a mechanism to achieve the loop, supposing that your current code is somewhere near what you want to achieve. But I found many mistakes so I had to refactor it, hopefully it will get you a step further.
The following code will continue looping until user presses Cancel in the file dialog box:
Sub prompt()
Dim d As VbMsgBoxResult: d = MsgBox("Add record?", vbYesNoCancel + vbInformation)
If d = vbNo Then
Sheets("MPSA").Range("a13").value = "No data Found"
Sheets("MPSA").Range("a13").Font.Bold = True
ThisWorkbook.Save
Exit Sub
End If
If d = vbCancel Then
Sheets("MPSA").Delete
ThisWorkbook.Save
Exit Sub
End If
On Error GoTo Cleanup
Application.DisplayAlerts = False: Application.EnableEvents = False: Application.ScreenUpdating = False
Sheets("MPSA").Range("a14:ac14").value = Array( _
"NAME", "NUMBER", "AGR NUMBER", "ENTITY NAME", "GROUP", "DELIVERABLE", "DELIVERAB", "IS COMPON", _
"PACKAGE", "ORDERS", "LICNTITY", "QUANTITY", "ORDERANUMBER", "ORDERAM NAME", "PAC NUMBER", "PACKAGAME", _
"ITTION", "LICENSE TYPE", "ITEM VERSION", "REAGE", "CLIIT", "LICEAME", "ASSATE", "ASSTE", _
"ENTITTUS", "ASSGORY", "PURCHAYPE", "BILLTHOD", "SALETER")
Sheets("MPSA").Columns.AutoFit
Dim Target_Path: Target_Path = Application.GetOpenFilename
Do While Target_Path <> False ' <-- loop until user cancels
Dim Target_Workbook As Workbook: Set Target_Workbook = Workbooks.Open(Target_Path)
Target_Workbook.Sheets(1).Range("A1").CurrentRegion.Copy _
ThisWorkbook.Sheets("MPSA").Range("a1000000").End(xlUp).Offset(1)
Target_Workbook.Close False
ActiveCell.EntireRow.Delete
ThisWorkbook.Save
Target_Path = Application.GetOpenFilename
Loop
Cleanup:
If Err.Number <> 0 Then MsgBox "Something went wrong: " & vbCrLf & Err.Description
Application.DisplayAlerts = True: Application.EnableEvents = True: Application.ScreenUpdating = True
End Sub
I have a script in VBA that prints out certain user selected variables to a PPT template. In this sub:
Private Sub WarningInfo()
Call Dictionary.WarningInfo
'Sets the font for the warning information text.
With ActiveWindow.Selection.SlideRange.Shapes("WarningText1").TextFrame2.TextRange.Font
.Size = 24
.Name = "Calibri"
.Shadow.Visible = True
End With
ComboBoxList = Array(CStr(ComboBox3))
For Each Ky In ComboBoxList
'On Error Resume Next
'If nothing is selected in ComboBox3, do nothing and exit this sub.
If ComboBox3 = "" Then
Exit Sub
'Otherwise, if it has a selection, insert selected text.
Else
ActiveWindow.Selection.SlideRange.Shapes("WarningText1").TextFrame2.TextRange = vbCrLf & dict2.Item(Ky)(0)
End If
Next
Set dict2 = Nothing
End Sub
It will print out dict2.Item(Ky)(0) within the shape WarningText1. This variable is selected by the user in a GUI and it is pulled from a dictionary. An example of what would be selected and output is "No hail expected".
My next sub is this:
Private Sub WarningInfo2()
Call Dictionary.WindInfo
'Sets the font for the warning information text.
With ActiveWindow.Selection.SlideRange.Shapes("WarningText1").TextFrame2.TextRange.Font
.Size = 24
.Name = "Calibri"
.Shadow.Visible = True
End With
ComboBoxList = Array(CStr(ComboBox4))
For Each Ky In ComboBoxList
'On Error Resume Next
'If nothing is selected in ComboBox4, do nothing and exit this sub.
If ComboBox4 = "" Then
Exit Sub
'Otherwise, if it has a selection, insert selected text.
Else
ActiveWindow.Selection.SlideRange.Shapes("WarningText1").TextFrame2.TextRange = vbCrLf & dict3.Item(Ky)(0)
End If
Next
Set dict3 = Nothing
End Sub
It will print out dict3.Item(Ky)(0). However, with the way this second sub is set up, it will just overwrite the data from the first sub (since both subs are within the same UserForm). I need to find a way to change this line of code ActiveWindow.Selection.SlideRange.Shapes("WarningText1").TextFrame2.TextRange = vbCrLf & dict3.Item(Ky)(0) so that it ADDS this text to the existing text within the shape "WarningText1".
Any ideas?
Thanks!!
ActiveWindow.Selection.SlideRange.Shapes("WarningText1").TextFrame2.TextRange = ActiveWindow.Selection.SlideRange.Shapes("WarningText1").TextFrame2.TextRange & vBCrLf & dict3.Item(Ky) (0)