Using a variable within a formula - vba

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

Related

How to loop on range of rows in LibreOffice Calc spreadsheet, comparing cell values, setting cell values and deleting row, if condition is true

I have the following requirement in my LibreOffice Calc spreadsheet:
ForEach Row 'r' in selected range,
starting from the last row in the range,
and moving backwards (up) one row at a time,
do some cell value comparisons, and based on that, either skip the row,
or set some cell values, and delete the selected row,
then proceed with the same process, with the row just above that.
ie.,
Representing CellValue(Column[A], Row[r])
as A[r],
And Representing the row before (just above) that,
as A[r-1],
I need to do the following:
FOR (r = LastRowInSelectedRange; r>1; r=r-1) {
IF FollowingConditionsAreTrue (
(r > 1)
AND (A[r] IsEqualTo A[r-1])
AND (B[r] IsEqualTo C[r-1])
AND (E[r] IsEqualTo E[r-1])
) ThenDoTheFollowing {
SET C[r-1] = C[r]
DeleteRow(r)
} EndIF
} EndFOR
Question:
How can we implement this in LibreOffice Calc?
The following should do the trick. It assumes your data are in the range A1:E10 in a sheet called Sheet1. To use a different range change the appropriate lines. If you want to select the range by hand, comment out the line oCellRange = oSheet.getCellRangeByName("A1:E10") and uncomment the line oCellRange = oDoc.getCurrentSelection(). That will only work if you have a single selection, not multiple ones.
Sub iterateThroughRange()
Dim oDoc As Object
oDoc = ThisComponent
Dim oSheet As Object
oSheet = oDoc.getSheets().getByName("Sheet1")
Dim oCellRange As Object
oCellRange = oSheet.getCellRangeByName("A1:E10")
'The above line gets a named range. To get a slected area instead
'comment it out and uncomment the following line:
'oCellRange = oDoc.getCurrentSelection()
Dim oTableRows As Object
oTableRows = oCellRange.getRows()
Dim nRows As Integer
nRows = oTableRows.getCount()
Dim oTableColumns As Object
oTableColumns = oCellRange.getColumns()
Dim nColumns As Integer
nColumns = oTableColumns.getCount()
Dim oThisRow As Object, oPreviousRow As Object
Dim oThisRowData() As Variant, oPreviousRowData() As Variant
Dim oThisRowAddress As Variant
For r = nRows - 1 To 1 Step - 1
oThisRow = oCellRange.getCellRangeByPosition(0, r, nColumns - 1, r)
oThisRowData = oThisRow.getDataArray()
oPreviousRow = oCellRange.getCellRangeByPosition(0, r - 1, nColumns - 1, r - 1)
oPreviousRowData = oPreviousRow.getDataArray()
'Column A = index 0
'Column B = index 1
'Column C = index 2
'Column E = index 4
If oThisRowData(0)(0) = oPreviousRowData(0)(0) AND _
oThisRowData(0)(1) = oPreviousRowData(0)(2) AND _
oThisRowData(0)(4) = oPreviousRowData(0)(4) Then
oPreviousRowData(0)(2) = oThisRowData(0)(2)
oPreviousRow.setDataArray(oPreviousRowData)
'The following two lines delete the range and move the cells up
oThisRowAddress = oThisRow.getRangeAddress()
oSheet.removeRange(oThisRowAddress, com.sun.star.sheet.CellDeleteMode.UP)
'To delete the entire row instead of just the affected cells,
'comment out the above two lines and uncomment the following line:
'oTableRows.removeByIndex(r, 1)
End If
Next r
End Sub

Word Template : Overwrite bookmark Information

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

Define a range using an existing named range & offset/resize

I am trying to use an existing named range to reference different rows (the columns should be the same). Right now I have the following:
Dim DetailONE, DetailONW, DetailW, DetailQc As Range
Set DetailONE = Sheet11.Range("CM12:EG13")
Set DetailONW = Sheet11.Range("EI12:GC13")
Set DetailW = Sheet11.Range("GE12:HO13")
Set DetailQc = Sheet11.Range("HQ12:IT13")
And then I refer to those named ranges but I get an Application defined or object defined error with the following. Does anyone know why? I don't know if I need the .Address part afterwards either or if I can forego this.
Dim OntarioWestDet, OntarioEastDet, WestDet, QuebecDet As Range
Set OntarioWestDet = Sheet11.Range(DetailONW.Address).Offset(3, 0).Resize(300, 0)
Set OntarioEastDet = Sheet11.Range(DetailONE).Offset(3, 0).Resize(300, 0)
Set WestDet = Sheet11.Range(DetailWe).Offset(3, 0).Resize(300, 0)
Set QuebecDet = Sheet11.Range(DetailQc).Offset(3, 0).Resize(300, 0)
This works for me (there is a typo in one of your names
Sub x()
Dim DetailONE As Range, DetailONW As Range, DetailW As Range, DetailQc As Range
Set DetailONE = Sheet11.Range("CM12:EG13")
Set DetailONW = Sheet11.Range("EI12:GC13")
Set DetailW = Sheet11.Range("GE12:HO13")
Set DetailQc = Sheet11.Range("HQ12:IT13")
Dim OntarioWestDet As Range, OntarioEastDet As Range, WestDet As Range, QuebecDet As Range
Set OntarioWestDet = DetailONW.Offset(3, 0).Resize(300)
Set OntarioEastDet = DetailONE.Offset(3, 0).Resize(300)
Set WestDet = DetailW.Offset(3, 0).Resize(300)
Set QuebecDet = DetailQc.Offset(3, 0).Resize(300)
End Sub

Object required error in Set =

I am trying to build some code that inserts a name and email address in to the next open row from the next row in the loop. I am getting an error in Set = Number of Emails line and I am not sure why.
Sub Email_Copy()
Dim Data As Worksheet
Set Data = ActiveWorkbook.Sheets("Data")
Dim Email_Database As Worksheet
Set Email_Database = ActiveWorkbook.Sheets("Email_Database")
Dim Number_Of_Emails As Integer
Set Number_Of_Emails = Data.Range("L6002")
Dim Total_Emails As Long
Set Total_Emails = Email_Database.Range("D2")
Dim X As Long
For X = 1 To Number_Of_Emails
Set Email_Database.Range("B3").Offset(Total_Emails, 0) = Data.Range("D3").Offset(Number_Of_Emails, 0)
End Sub
You declared Number_Of_Emails As Integer but then tried to set it to a range so it's a type mismatch. You can simply do
Number_Of_Emails = Data.Range("L6002").value
Edit: to plagarize Scott Holtzman's comment verbatim
Set is only required with Object Type variables (hence the error). A
Range variable is an Object Type. An Integer, being a number, is not
an object type. (String is not on object either). Worksheet is an
Object Type.

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