Iterating through all the cells in Excel VBA or VSTO 2005

后端 未结 9 1585
既然无缘
既然无缘 2020-12-03 07:15

I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells. The cells may contain text, numbers or be blank. I am not very familiar

相关标签:
9条回答
  • 2020-12-03 07:52

    My VBA skills are a little rusty, but this is the general idea of what I'd do.
    The easiest way to do this would be to iterate through a loop for every column:

    public sub CellProcessing()
    on error goto errHandler
    
        dim MAX_ROW as Integer   'how many rows in the spreadsheet
        dim i as Integer
        dim cols as String
    
        for i = 1 to MAX_ROW
            'perform checks on the cell here
            'access the cell with Range("A" & i) to get cell A1 where i = 1
        next i
    
    exitHandler:
        exit sub
    errHandler:
        msgbox "Error " & err.Number & ": " & err.Description
        resume exitHandler
    end sub
    

    it seems that the color syntax highlighting doesn't like vba, but hopefully this will help somewhat (at least give you a starting point to work from).

    • Brisketeer
    0 讨论(0)
  • 2020-12-03 07:56

    If you're just looking at values of cells you can store the values in an array of variant type. It seems that getting the value of an element in an array can be much faster than interacting with Excel, so you can see some difference in performance using an array of all cell values compared to repeatedly getting single cells.

    Dim ValArray as Variant
    ValArray = Range("A1:IV" & Rows.Count).Value
    

    Then you can get a cell value just by checking ValArray( row , column )

    0 讨论(0)
  • 2020-12-03 07:57

    You basically can loop over a Range

    Get a sheet

    myWs = (Worksheet)MyWb.Worksheets[1];
    

    Get the Range you're interested in If you really want to check every cell use Excel's limits

    The Excel 2007 "Big Grid" increases the maximum number of rows per worksheet from 65,536 to over 1 million, and the number of columns from 256 (IV) to 16,384 (XFD). from here http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel

    and then loop over the range

            Range myBigRange = myWs.get_Range("A1", "A256");
    
            string myValue;
    
            foreach(Range myCell in myBigRange )
            {
                myValue = myCell.Value2.ToString();
            }
    
    0 讨论(0)
提交回复
热议问题