Selecting non-blank cells in Excel with VBA

前端 未结 4 544
借酒劲吻你
借酒劲吻你 2020-12-09 19:16

I\'m just beginning to dive into VBA and I\'ve hit a bit of a roadblock.

I have a sheet with 50+ columns, 900+ rows of data. I need to reformat about 10 of those col

4条回答
  •  忘掉有多难
    2020-12-09 19:49

    The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.

    Option Explicit
    
    Public Sub exportDataToNewBook()
        Dim rowIndex As Integer
        Dim colIndex As Integer
        Dim dataRange As Range
        Dim thisBook As Workbook
        Dim newBook As Workbook
        Dim newRow As Integer
        Dim temp
    
        '// set your data range here
        Set dataRange = Sheet1.Range("A1:B100")
    
        '// create a new workbook
        Set newBook = Excel.Workbooks.Add
    
        '// loop through the data in book1, one column at a time
        For colIndex = 1 To dataRange.Columns.Count
            newRow = 0
            For rowIndex = 1 To dataRange.Rows.Count
                With dataRange.Cells(rowIndex, colIndex)
    
                '// ignore empty cells
                If .value <> "" Then
                    newRow = newRow + 1
                    temp = doSomethingWith(.value)
                    newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
                    End If
    
                End With
            Next rowIndex
        Next colIndex
    End Sub
    


    Private Function doSomethingWith(aValue)
    
        '// This is where you would compute a different value
        '// for use in the new workbook
        '// In this example, I simply add one to it.
        aValue = aValue + 1
    
        doSomethingWith = aValue
    End Function
    

提交回复
热议问题