简体   繁体   中英

Unable to turn VBA string into Excel cell formula

Tring to make the following code work. For some reason returns a Run-time error '1004': Application-defined or object-defined error.

The code is the following:

Sub UpdateLinks()
Dim lastFlight, lastMis, logBook, studentCode As String
Dim i, j, k, numRows As Integer
Dim wb0 As Workbook
Dim studentSheet As Worksheet

Set wb0 = ActiveWorkbook

Set studentSheet = wb0.Worksheets("STUDENTS")

numRows = studentSheet.Range("A5").CurrentRegion.Rows.Count

studentCode = studentSheet.Cells(8, 2).Value

lastFlight = "=MAIOR('\\server\# FLTLOG_EXPORT\[" & studentCode & ".xlsx]Status'!$A$3:$A$219;1)"
lastMis = "=PROC(2;1/(1-É.CÉL.VAZIA('\\server\# FLTLOG_EXPORT\[" & studentCode & ".xlsx]Status'!$C$3:$C$230));'\\server\# FLTLOG_EXPORT\[" & studentCode & ".xlsx]Status'!$C$3:$C$230)"
logBook = "'\\server\# FLTLOG_EXPORT\[" & studentCode & ".xlsx]Desvios'!$Q$15"

ActiveSheet.Cells(8, 4).Formula = lastFlight

End Sub

The formulas are in Portuguese and MAIOR is LARGE, PROC is LOOKUP. The code stops in the:

ActiveSheet.Cells(8, 4).Formula = lastFlight

Please help. Kind regards.

First of all please note that if you declare

Dim i, j, k, numRows As Integer

only numRows is Integer but all the others are of type Variant . It is exactly the same as writing:

Dim i As Variant, j As Variant, k As Variant, numRows As Integer

In VBA you need to specify a type for every variable. Also Excel has more rows than fit into an Integer , so you must use Long instead. Also there is no benefit in using Integer in VBA so I recommend always to use Long instead:

Dim i As Long, j As Long, k As Long, numRows As Long

Same applies to your other multiple variables declared in one line.


Another recommendation is to avoid ActiveWorkbook and ActiveSheet if possible. Note that ActiveWorkbook is the workbook that has focus / is on top. This can change easily by a single user click. What you probably meant to use is ThisWorkbook which is the workbook this VBA code is written in (and it never changes).

Instead of ActiveSheet.Cells specify the worbkook and worksheet explicitly for your Cells object. Like studentSheet.Cells or something similar.


To your actual issue

Note that the file studentCode & ".xlsx needs to be open if you want to use it in a formula.

Make sure you open it with

Dim wb As Workbook
Set wb = Workbooks.Open("\\server\# FLTLOG_EXPORT\" & studentCode & ".xlsx"

Then you can use it in your formula without the path:

lastFlight = "=MAIOR('[" & studentCode & ".xlsx]Status'!$A$3:$A$219;1)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM