Word Template : Overwrite bookmark Information - vba

I have a template, when opened opens up a user-form for specified data. But how can I delete the data inputted (bookmarks), if I want to rerun the macro to add new data. Currently it just adds on to whatever is filled.
Private Sub Cancelbut_Click()
PInfo.Hide
End Sub
Private Sub OKbut_Click()
Dim CompamyName As Range
Dim CompanyName2 As Range
Set CompanyName = ActiveDocument.Bookmarks("CName").Range
Set CompanyName2 = ActiveDocument.Bookmarks("CName2").Range
CompanyName.Text = Me.TextBox1.Value
CompanyName2.Text = Me.TextBox1.Value
Dim VendorName As Range
Set VendorName = ActiveDocument.Bookmarks("VName").Range
VendorName.Text = Me.TextBox2.Value
Dim ProjectName As Range
Dim ProjectName2 As Range
Set ProjectName = ActiveDocument.Bookmarks("PName").Range
Set ProjectName2 = ActiveDocument.Bookmarks("PName2").Range
ProjectName.Text = Me.TextBox3.Value
ProjectName2.Text = Me.TextBox3.Value
Dim ProjectCode As Range
Set ProjectCode = ActiveDocument.Bookmarks("PCode").Range
ProjectCode.Text = Me.TextBox4.Value
Me.Repaint
PInfo.Hide
End Sub
How would someone go about clearing the existing data? Feel like this would help anyone trying to work with bookmarks in word. I have attempted to do it, but end up deleting the bookmarks.
Appreciate the help!

Writing to a bookmark (whether as a user or using code) deletes the bookmark - this is by-design. When working with VBA, however, you have a work-around not easily available to the user...
If you first assign a Range object to the bookmark's Range, the text you assign to the Range can subsequently be bookmarked again. Since you write to numerous bookmarks, best to put these actions into a separate procedure, rather than repeat them throughout your code, as proposed below.
Tip: You can save yourself some code if you put REF fields (cross-references) in for the second bookmarks, where you write the information twice.
Function WriteToBookmarkRetainBookmark(rng As Object, content As String)
Dim sBkmName As String
sBkmName = rng.Bookmarks(1).Name
rng.Text = content
rng.Document.Bookmarks.Add sBkmName, rng
End Function
Private Sub OKbut_Click()
Dim CompamyName As Range
Dim CompanyName2 As Range
Set CompanyName = ActiveDocument.Bookmarks("CName").Range
Set CompanyName2 = ActiveDocument.Bookmarks("CName2").Range
WriteToBookmarkRetainBookmark(CompanyName, Me.TextBox1.Value)
WriteToBookmarkRetainBookmark(CompanyName2, Me.TextBox1.Value)
Dim VendorName As Range
Set VendorName = ActiveDocument.Bookmarks("VName").Range
WriteToBookmarkRetainBookmark(VendorName, Me.TextBox2.Value)
Dim ProjectName As Range
Dim ProjectName2 As Range
Set ProjectName = ActiveDocument.Bookmarks("PName").Range
Set ProjectName2 = ActiveDocument.Bookmarks("PName2").Range
WriteToBookmarkRetainBookmark(ProjectName, Me.TextBox3.Value)
WriteToBookmarkRetainBookmark(ProjectName2, Me.TextBox3.Value)
Dim ProjectCode As Range
Set ProjectCode = ActiveDocument.Bookmarks("PCode").Range
WriteToBookmarkRetainBookmark(ProjectCode, Me.TextBox4.Value)
Me.Repaint
PInfo.Hide
End Sub

Related

Using a variable within a formula

I'm trying to use a variable within a formula but the result I am getting is FALSE, when it should be returning a Lookup value, starting from the bottom of a table and going up.
Private Sub NewTaxCode()
Dim TaxCode2 As Long
Dim B As Range
Dim TaxCode3 As Range
Dim TaxCode4 As Range
Worksheets("P11Combined").Activate
Set B = Range("A:A")
Worksheets("E'ee Details").Range("U1").Value = "=Match(RC[-4],P11Combined!C[-18],0)"
TaxCode2 = Worksheets("E'ee Details").Range("U1").Value
Set TaxCode3 = Range("A:A").Find(What:="TAX:", After:=B(TaxCode2))
Set TaxCode4 = Range(TaxCode3.Address).End(xlDown).Offset(1, 2)
TaxCode5 = Range(TaxCode4.Address).FormulaR1C1 = "=LOOKUP(2,1/(R[-12]C:R[-1]C<>"" ""),(R[-12]C[-1]:R[-1]C[-1]))"
The last line is where I am having the issues. The formula works fine on a spreadsheet but I can't get it to work in VBA.
The last line of your code is of the format
variable = logical_expression
and is setting a variable (TaxCode5) to be either True or False depending on whether or not the formula in the cell referred to by TaxCode4 is the same as the one in the code.
It does not modify the formula in the cell referred to by TaxCode4.
It appears you want:
Private Sub NewTaxCode()
Dim TaxCode2 As Long
Dim B As Range
Dim TaxCode3 As Range
Dim TaxCode4 As Range
Dim TaxCode5 As Variant
Set B = Worksheets("P11Combined").Range("A:A")
Worksheets("E'ee Details").Range("U1").FormulaR1C1 = "=Match(RC[-4],P11Combined!C[-18],0)"
TaxCode2 = Worksheets("E'ee Details").Range("U1").Value
Set TaxCode3 = B.Find(What:="TAX:", After:=B(TaxCode2))
Set TaxCode4 = TaxCode3.End(xlDown).Offset(1, 2)
TaxCode4.FormulaR1C1 = "=LOOKUP(2,1/(R[-12]C:R[-1]C<>"" ""),(R[-12]C[-1]:R[-1]C[-1]))"
TaxCode5 = TaxCode4.Value
'...
End Sub

CATIA VBA Measure a user selected line(s)/spline

I am trying to get the length of user selected lines/splines
This is the code I'm using to have users select their lines:
Dim USel As Selection
Dim USelLB
Dim InputObject(0)
InputObject(0) = "AnyObject"
Set USel = CATIA.ActiveDocument.Selection
Set USelLB = USel
USel.Clear
USelLB.Clear
Linestomeasure = USelLB.SelectElement3(InputObject, "Select objects to list names", True, CATMultiSelTriggWhenUserValidatesSelection, False)
Linestomeasure is a public variable, in the mainsub i've been trying to measure Linestomeasure using the following code:
Dim pd1 As PartDocument
Dim a As Object
Dim c As Reference
a = TrimLines.Item(1)
c = pd1.Part.CreateReferenceFromObject(a)
Dim Mea1 As Measurable
Dim TheSPAWorkbench As SPAWorkbench
Set TheSPAWorkbench = pd1.GetWorkbench("SPAWorkbench")
Set Mea1 = TheSPAWorkbench.GetMeasurable(c)
But when I run the code a = trimLines.Item(1) gets highlighted in the debugger with the error message "Object Required".
Does anyone have an idea on how I can change my code so that I can get the length of the line as a variable that I can work with ? Or just a different way to go about what I'm trying to do?
Edited answer to reflect comment bellow
Looks like you are assigning the wrong type of variable to the USelLB.SelectElement3 and also missunderstanding how it actually works.
The Selection.SelectElement3 returns a String that reflects whether the selection was sucessfull or not.
The Object retrieved from the Selection is inside the Selection.Item(Index)
Your code should be something like this:
Dim PD1 as PartDocument
Dim Sel 'as Selection 'Sometimes it is needed to comment the selection to use the .SelectElement3 method
Dim InputObjType(0)
Dim SelectionResult as string
Dim LineToMeasure as AnyObject
Dim I as Integer
Dim SpaWorkbench as SPAWorkbench
Dim Measurable as Measurable
InputObjType(0) = "AnyObject"
'set PD1 = Catia.ActiveDocument
set Sel = PD1.Selection
Set TheSPAWorkbench = pd1.GetWorkbench("SPAWorkbench")
Sel.Clear
SelectionResult= Sel.SelectElement3(InputObject, "Select objects to list names", True, CATMultiSelTriggWhenUserValidatesSelection, False)
If SelectionResult = "Ok" or SelectionResult = "Normal" then 'Check if user did not cancel the Selection
For i = 1 to Selection.Count
Set LineToMeasure = Sel.Item(i).Value
set Measurable = SpaWorkbench.GetMeasurable(LineToMeasure)
'Measure whatever you need here.
Next
End If
Keep in mind that using the AnyObject type filter may cause the user to select unwanted objects. You shoudl use a more specific filter.

Excel vba -- Object required error at Sub line

So I am getting an error at the beginning of my code, an error I didn't use to get last time I opened and edited my VBA code. Any ideas? Here is part of it. When I try to step through the code, I get the error: "Object required" and my sub line (first line) is highlighted. Any ideas how I can fix this?
Sub ManagerCashflow()
'---------------------------Declare all the variables---------------------------
'------Define object names------
'Dim i As Integer
'Dim c As Integer
Dim AUM_Cash_Projections_folder_pathname As String
Dim AUM_Cash_Projections_FOLDER_YEARMONTH_pathname As String
Dim AUM_Cash_Projections_filename_DATE As String
Dim AUMCshf_wb As Workbook
Dim MngrCshF_wb As Workbook
'Dim CshF_lr As Integer
'Dim PE_r As Integer
'Dim lstmanager_r As Integer
'------Set/call the objects to a destination------
'Worksheets
'Manager Cashflow
Set MngrCshF_wb = ThisWorkbook
Set MCF_Current_ws = MngrCshF_wb.Sheets("Sheet1")
'AUM Cash Projections
Set AUM_Cash_Projections_folder_pathname = "https://iportal.casey.org/Risk Management/CFP Reporting/AUM Cash Projection"
Set AUM_Cash_Projections_FOLDER_YEARMONTH_pathname = Right(MCF_Current_ws.Cells(2, 1).Value, 7)
Set AUM_Cash_Projections_filenamedate = MCF_Current_ws.Cells(2, 1).Value
Set AUMCshf_wb = Workbooks.Open(AUM_Cash_Projections_folder_pathname + "/" + AUM_Cash_Projections_FOLDER_YEARMONTH_pathname + "/" + AUM_Cash_Projections_filenamedate)
Set CshF_ws = AUMCshf_wb.Sheets("CashFlow + Projections")
'Master Data with all of the current managers
Set CurrAssets_ws = AUMCshf_wb.Sheets("Master Data")
'... a bunch of other code that works....
End Sub
Not sure why it didn't happen before. You don't need to use set to assign a value to a string.
AUM_Cash_Projections_folder_pathname = "https://iportal.casey.org/Risk Management/CFP Reporting/AUM Cash Projection"
AUM_Cash_Projections_FOLDER_YEARMONTH_pathname = Right(MCF_Current_ws.Cells(2, 1).Value, 7)
AUM_Cash_Projections_filenamedate = MCF_Current_ws.Cells(2, 1).Value
You also need to declare MCF_Current_ws and your other worksheets. It won't tell you unless you have "Option Explicit" at the top of your code, but it's good to do.
Dim MCF_Current_ws as Excel.Worksheet

Getting the cell value of two string variables

I have a 2D chart in Excel. I need to get the value of a cell using two string variables. The chart looks like this:
Document person1 person2
Text1 5 8
Text2 2 1
Text3 9 6
After looking online I am finding this difficult because:
the values are strings, not integers;
the strings will change depending on which person and document combination comes up.
This should be the only code that is relevant:
Dim document as string
Dim person as string
Dim oExcel as excel.application
Dim oWB as workbook
Set oExcel = New Excel.application
Set oWB = oExcel.Workbooks.open. ("C:")
oExcel.Visible = True
oWB.Sheets ("sheet1").Cells(documemt, person)
Assuming that document and person are string variables that hold string representations of integers (e.g. document = "1", person = "2") then something like
oWB.Sheets ("sheet1").Cells(val(document), val(person))
will work. If the contents of the string variables are more complicated then you would need to do some parsing of those strings.
Assuming by "2d Chart" you mean a table in a Worksheet, and that person would be the full text "person1", or "person2", etc. and likewise for document, then perhaps this function will do the trick.
Function FindDocPerson(person As String, document As String) As Variant
Const MatchExact As Integer = 0
Dim ws As Excel.Worksheet
Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim table As Excel.Range
Set table = ws.UsedRange
Dim docRange As Excel.Range
Set docRange = table.Columns(1).Offset(1, 0).Resize(table.Columns(1).Rows.Count - 1)
Dim personRange As Excel.Range
Set personRange = table.Rows(1).Offset(0, 1).Resize(1, table.Columns.Count - 1)
Dim personIndex As Long
Dim docIndex As Long
On Error GoTo errHandler
personIndex = Application.WorksheetFunction.Match(person, personRange, MatchExact) + 1
docIndex = Application.WorksheetFunction.Match(document, docRange, MatchExact) + 1
FindDocPerson = table.Cells(docIndex, personIndex).Value2
Exit Function
errHandler:
FindDocPerson = VBA.CVErr(Excel.xlErrNA)
End Function
calling syntax:
Dim result As Variant
result = FindDocPerson("person2", "text1")
If Application.WorksheetFunction.IsError(result) Then
' handle it
Else
' found it
End If
There is a typo in your code,
oWB.Sheets ("sheet1").Cells(documemt, person)
documemt should be document
All that aside though it is unclear what you want to do, can you give a little more description please?
All we know is you need to get the value of a cell using two string variables and that it could be a string or a number. The code you posted doesn't give much more of a hint to your goal.
To convert between strings and numbers you can use CLng to convert to a long number or CStr to convert to a string. eg CLng("3") = 3 and CStr(3) = "3"
In your code this:
Set oWB = oExcel.Workbooks.open. ("C:")
Doesn't work because you are trying to open a workbook without specifying a name, I also note the ("C:") is spaced far to the right of the command call which leads me to believe this is has been typed freestyle ie not in the VBE. This makes it even harder to decode into your requirements.
Lastly, this code:
Set oExcel = New Excel.application
Why are you starting another session of Excel from Excel VBA code? Is this code somewhere other than Excel ie Outlook / Access / PowerPoint / Word / Business Objects etc etc.

Excel VBA using Combobox with Index Match

I have an Excel VBA UserForm Combobox for scanning asset tags to compare against a site baseline held in Sheet1. There can be upto 50,000+ assets. The named ranges are all correct.
I want the loop to fill the "Found" Asset attribute Textboxes for Type, Serial, MakeModel, Location & PrinterHost.
The code is below without the additional index match lookups for extra asset attributes as the process will be the same. Help appreciated as I'm not sure where I'm going wrong. Thanks in advance.
Private Sub ComboScanTag_Change()
Dim x As Integer
Dim AssetCount As Long
Dim BASELINE As Range
Dim AssetID As Range
Dim FoundType As Variant
Dim FoundSerial As Variant
Dim FoundMakeModel As Variant
Dim FoundLocation As Variant
Dim FoundPrinterHostName As Variant
If Me.ComboScanTag.Value = "" Then 'ScanTag has no value
MsgBox "Asset not Found - Re-Scan or enter New Asset details"
Me.ComboScanTag.SetFocus
End If
If Me.ComboScanTag.Value <> "" Then 'ScanTag has a value
Application.ScreenUpdating = False 'Turn off screen updating to speed app
For x = 1 To AssetCount 'Number of loop iterations from Baseline Assets Count D1 cell
FoundType = Application.Index("BASELINE", Application.Match(Me.ComboScanTag.Value, "AssetID", False), 3)
If Not IsError(FoundType) = False Then 'if error value in lookup return 0
Me.txtFoundType.Value = FoundType 'Fill textbox FoundType with lookup value from baseline
Else
On Error GoTo 0 'reset error handler
FoundSerial = Application.Index("BASELINE", Application.Match(Me.ComboScanTag.Value, "AssetID", False), 11)
If Not IsError(FoundSerial) = False Then
Me.txtFoundSerial.Value = FoundSerial
End If
Next x
End If
Application.ScreenUpdating = True
End Sub
AssetCount is not initialized. You need to initialize it before you use it like AssetCount = 10.
BASELINE and AssetID are not set as well.
If BASELINE and AssetID are named ranges, you cannot use it the way you do in Application.Index or Application.Match.
You need to pass it as object and not as string like this:
Set BASELINE = ThisWorkbook.Names("BASELINE").RefersToRange
Set AssetID = ThisWorkbook.Names("AssetID").RefersToRange
Then you can use it like this in Application.Index and Match:
With Application
FoundType = .Index(BASELINE, .Match(Me.ComboScanTag.Value, AssetID, False), 3)
End With