how to count non empty cells in macro

匆匆过客 提交于 2019-12-25 07:15:39

问题


Hi i have come up with a code to open multiple workbooks. The code is

Sub OPEN_hari()
Dim r As Long
For r = 1 To 10
    Workbooks.Open Filename:=Sheet2.Cells(r, 1).Value
Next r
End Sub

But the problem here is if only 3 cells ((1,1) (2,1) (3,1)) has the path of the workbook files, an error message is thrown that coulndt open "" files. How can i make this macro to open only the files that are mentioned without error message. As i am beginner in this any help is highly appreciated


回答1:


There're two ways of getting what you need:

  1. Run an infinite loop, checking the emptiness of a cell:

    Dim i as Long: i = 0 
    
    While Not IsEmpty(Sheet1.Cells(i + 1, 1)) 'assuming the value is in Column A
        'your code
        i = i + 1 
    Wend
    
  2. Get the number of used rows, however there's a risk that a cell might have been used, but is have no data now, so I'm including a check:

    Dim ur as Long: ur = Sheet1.UsedRange.Rows.Count
    Dim i as Long
    
    For i = 0 to (ur - 1)
         If LenB(Sheet1.Cells(i + 1, 1).Value) > 0 then
            'your code
         End If 
    Next i
    


来源:https://stackoverflow.com/questions/15770574/how-to-count-non-empty-cells-in-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!