如何在excel vba中检查其他工作簿的单元格值是否为空

时间:2014-09-04 06:51:43

标签: excel vba

Dim ConsolidateSheetObj As Workbook
Dim str As String
Dim keycount,row As Interger

Set ConsolidateSheetObj = Workbooks.open("filePath")

Set str = ConsolidateSheetObj.Sheets(3).Cells(row, 17 + keycount).Value

If str.IsEmpty() Then
. . .
...

End If

2 个答案:

答案 0 :(得分:0)

强制转换为字符串并检查其长度是一种不好的方法。此外,您使用Set str在语法上无效:Set仅用于对象类型。

更好的方法是:

Dim v as Variant
v = ConsolidateSheetObj.Sheets(3).Cells(row, 17 + keycount).Value
If VarType(v) = vbEmpty Then
    'this is an empty range
End If

答案 1 :(得分:0)

Sub checkEmpty()
    'Used variables
    Dim filePath As String
    Dim sheet, row, keycount As Integer
    Dim cellEmpty As Boolean

    'Disable Screen updates
    Application.ScreenUpdating = False

    filePath = "C:\Your_file.xlsx"
    sheet = 3
    row = 3
    keycount = 2
    cellEmpty = False

    'Open other workbook
    Workbooks.Open Filename:= _
        filePath
    'Check if cell is empty
    If isEmpty(Sheets(sheet).Cells(row, 17 + keycount)) Then
        cellEmpty = True
    End If

    'Close other workbook
    Application.DisplayAlerts = False
    ActiveWorkbook.Close SaveChanges:=No

    If cellEmpty Then
        MsgBox ("Cell is Empty!")
        '...Your Code here!
    End If

    'Enable Screen updates
    Application.ScreenUpdating = True

End Sub