首页 > 解决方案 > 打开excel文件时未设置对象变量或带有块变量

问题描述

因为我找不到增加下拉列表字体大小的方法,所以我必须找到一种解决方法。一种选择是放大。因此我有这段代码 - 完美运行。但是一旦我关闭文件并尝试重新打开它,就会出现一条错误消息:“未设置对象变量或块变量。”

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

On Error GoTo errorHandler

Dim xZoom As Long
xZoom = 60

If Target.Validation.Type = xlValidateList Then xZoom = 125

errorHandler:
ActiveWindow.Zoom = xZoom  'Debug highlights this row

End Sub

我尝试过:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

On Error GoTo errorHandler

Dim wb as Workbook

Dim xZoom As Long
xZoom = 60

Set wb = ThisWorkbook

wb.Activate

If Target.Validation.Type = xlValidateList Then xZoom = 125

errorHandler:
ActiveWindow.Zoom = xZoom  'Debug highlights this row

End Sub

但似乎没有任何效果......我只是不知道可能是什么原因......有人可以帮助我吗?

标签: excelvba

解决方案


在进行缩放之前检查 windows.count > 0。

If Application.Windows.Count > 0 Then
    ActiveWindow.Zoom = xZoom
End If

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    On Error GoTo errorHandler

    Dim xZoom As Long
    xZoom = 60

    If Target.Validation.Type = xlValidateList Then
        xZoom = 125
        If Application.Windows.Count > 0 Then
            ActiveWindow.Zoom = xZoom  'Debug highlights this row
        End If
    End If
Exit Sub 'must exit before the error handler
errorHandler:
    Msgbox(Err.Description)
End Sub

推荐阅读