I am working on an Excel VBA routine that needs to execute the formula:
CHOOSECOLS(matrix, col_num1; col_num2). However, after the formula is written in the cell, at the end of the VBA routine, it is not calculated, displaying the error: #NAME. The syntax of the formula is not wrong, since when pressing the F2 + Enter keys, the formula is calculated and displays the expected value, but it is not calculated in any other way unless pressing the F2 + Enter keys. What should I do to correct this error and have the formula calculated automatically?
The code written is shown bellow:
Function DeterminarRangeTabela() As Range
Dim wsBase As Worksheet
Set wsBase = ThisWorkbook.Sheets("1_BASE CARTEIRA")
' Determina a última linha e última coluna
Dim lastRow As Long
lastRow = wsBase.Cells(wsBase.Rows.Count, "A").End(xlUp).Row
Dim lastCol As Long
lastCol = wsBase.Cells(3, wsBase.Columns.Count).End(xlToLeft).Column
' Determina o range da tabela a partir da linha 3 até a última linha e última coluna com dados
Dim tblRange As Range
Set tblRange = wsBase.Range(wsBase.Cells(4, 1), wsBase.Cells(lastRow, lastCol))
' Retorna o range da tabela
Set DeterminarRangeTabela = tblRange
End Function
Dim tblRange As Range
Set tblRange = DeterminarRangeTabela()
Dim wsCarteira As Worksheet
Set wsCarteira = ThisWorkbook.Sheets("2_CARTEIRA")
Dim formula As String
formula = "=CHOOSECOLS('1_BASE CARTEIRA'!" & tblRange.Address(False, False) & ",4,1,5,6,7,8,9,2,3,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,47,45,46,48,49,50,51,52,53,54,55,56,57)"
wsCarteira.Range("A5").Formula2 = formula
wsCarteira.Range("A5").Calculate