使用公式连接引用会产生运行时错误

问题描述 投票:-1回答:2

我正在尝试使用VBA来连接公式中的字符串。如果我只使用下面的代码,我没有收到任何错误,但当我将IFERROR与代码一起添加时,我得到运行时错误。

有没有办法解决它?

text1 = "='C:\Users\JOHLA\\Desktop\Yield ark\Nyt-yield-ark\[Yield-Uge-"
text2 = ".xlsm]Scrap'!H7"

下面给出了包含带有运行时错误的IFERROR字符串的代码。

Private Sub CommandButton1_Click()

Dim ws As Worksheet
Dim i As Integer
Dim preRange As Range
Dim path, filename1 As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set ws = ActiveWorkbook.Sheets("Sheet1")
Set preRange = ws.Range("E9:I17")
i = ws.Range("C1").Value
text1 = "=IFERROR('C:\Users\JOHLA\Desktop\Yield ark\Nyt-yield-ark\[Yield-Uge-"
text2 = ".xlsm]Scrap'!H7;0)"

With ws
    For i = .Range("C1").Value To .Range("C1").Value + 4
        debug.print text1 & i & text2
        preRange = text1 & i & text2
        Set preRange = preRange.Offset(0, 5)
    Next i
End With

End Sub
excel vba excel-formula
2个回答
1
投票

通过在公式中使用分号判断,这表明您使用的是与VBA不兼容的本地设置.Formula

在这种情况下,您需要更改公式以使用逗号或使用FormulaLocal设置公式:

preRange.FormulaLocal = Replace(text1 & i & text2, "'", Chr(34))

正如你所看到的,我还添加了一个将Replace改为'" - 我认为你也需要它。

最后,不要忘记在日常工作结束时启用ScreenUpdatingDisplayAlerts


0
投票

任何时候你使用

Application.ScreenUpdating = False 
Application.DisplayAlerts = False

如果代码中断,您需要确保使用错误处理来管理。

On Error GoTo ExitErr

   Application.ScreenUpdating = False 
   Application.DisplayAlerts = False
   <your code here>

ExitErr:
   Application.ScreenUpdating = True
   Application.DisplayAlerts = True

这可以确保如果您的代码中断(在您的情况下最明显的是某人重命名为“Sheet1”),Excel不会保留ScreenUpdating并且DisplayAlerts保持关闭状态。我无法告诉你有多少次我必须修复其他人的代码,因为他们关闭了这些功能,然后无法弄清楚为什么Excel会起作用。

© www.soinside.com 2019 - 2024. All rights reserved.