这里我得到问题返回1010逻辑测试。它应检查范围内的每个单元格,如果单元格包含数字则退出循环。如果范围内的任何单元格包含值,则返回1,如果所有单元格都为空,则返回0。我尝试了工作表函数CountIf,CountA,Not IsEmpty,IsText但结果不同似乎空白单元格包含不可见的字符串。 IsNumeric适用于单个单元格,但是当范围包括它不起作用时。我还注意到我第一次运行它,它产生结果,第二次运行导致错误。请帮助,我的范围需要变量。
Sub Try()
Dim path As String, myfile As String, file As String
Dim wb As Workbook
Dim i As Integer
Dim NCell As Range
Dim IsNumber As Boolean
path = "E:\SouthNorth\"
myfile = path & "1979.xls"
file = Dir(myfile)
Set wb = Workbooks.Open(Filename:=path & file)
wb.Activate 'necessary?
i = 24
'here object defined error
For Each NCell In Worksheets("Sheet1").Range(Cells(i, 2), Cells(i, 4))
If IsNumeric(NCell) Then
IsNumber = True
If IsNumber = True Then Exit For
End If
Next NCell
Select Case IsNumber
Case True
wb.Worksheets("Sheet2").Range("B" & i) = 1
Case False
wb.Worksheets("Sheet2").Range("B" & i) = 0
End Select
End Sub
答案 0 :(得分:0)
你可以使用'CountBlank' - 如果列范围总是3个单元格,那么你可以声明一个布尔值并从3中减去空白数,如果所有单元格都是空白或任何大于0的值,则给出0(假) )如果至少有一个单元被占用:
Dim x As Boolean
x = 3 - Application.WorksheetFunction.CountBlank(Worksheets("Sheet1").Range(Cells(i, 2), Cells(i, 4)))
MsgBox x
如果它特定于数值(例如忽略文本),那么只需添加到您的IsNumeric线:
If IsNumeric(ncell) And Not ncell = "" Then
答案 1 :(得分:0)
我认为这属于评论,但我不允许......
您提到您的问题是当您尝试运行 秒时 时间 ,这意味着错误可能来自vba试图打开 你的文件已经打开。其他一切似乎都有效
忽略这一切,这是我原来的答案"但我不知道如何格式化strikethough,我不想删除所有。
试试此代码
Sub Try()
Dim wb As Workbook
Dim path As String
Dim i As Integer, j As Integer
Dim NCell As Range
path = "E:\SouthNorth\1979.xls"
Set wb = Workbooks.Open(Filename:=path)
wb.Activate
i = 24
Sheets("Sheet2").Range("B" & i).Value = 0
For j = 2 To 4
Set NCell = Sheets("Sheet1").Cells(i, j)
If IsNumeric(NCell.Value) Then
Sheets("Sheet2").Range("B" & i).Value = 1
Exit For
End If
Next j
End Sub
答案 2 :(得分:0)
首先,让Cell定义一个没有父工作表的Range对象是一个非常糟糕的做法。有关详细信息,请参阅Is the . in .Range necessary when defined by .Cells?。
Worksheets("Sheet1").Range(Cells(24, 2), Cells(24, 4))
您似乎特别想要数字计数。引入工作表的COUNT函数就可以了。
With Worksheets("Sheet1")
With .Range(.Cells(24, 2), .Cells(24, 4))
Worksheets("Sheet2").Range("B" & i) = Abs(CBool(Application.Count(.Cells)))
End With
End With
使用带有xlNumbers的xlCellTypeConstants,你也可以使用SpecialCells严格保持在VBA内。
Dim rng As Range
With Worksheets("Sheet1")
On Error Resume Next
Set rng = .Range(.Cells(24, 2), .Cells(24, 4)).SpecialCells(xlCellTypeConstants, xlNumbers)
On Error GoTo 0
If Not rng Is Nothing Then
Worksheets("Sheet2").Range("B" & i) = 1
Else
Worksheets("Sheet2").Range("B" & i) = 0
End If
End With