简体   繁体   English

使用 VBA 在 Excel 中选择非空白单元格

[英]Selecting non-blank cells in Excel with VBA

I'm just beginning to dive into VBA and I've hit a bit of a roadblock.我刚刚开始深入研究 VBA,但遇到了一些障碍。

I have a sheet with 50+ columns, 900+ rows of data.我有一张包含 50 多列、900 多行数据的工作表。 I need to reformat about 10 of those columns and stick them in a new workbook.我需要重新格式化其中大约 10 个列并将它们粘贴到新的工作簿中。

How do I programmatically select every non-blank cell in a column of book1, run it through some functions, and drop the results in book2?如何以编程方式选择 book1 列中的每个非空白单元格,通过一些函数运行它,并将结果放到 book2 中?

I know I'm am very late on this, but here some usefull samples:我知道我已经很晚了,但这里有一些有用的示例:

'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select

or或者

'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
    .value = .value
end with

To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data).要查找列中最后使用的行,永远不要依赖 LastCell,这是不可靠的(删除数据后不会重置)。 Instead, I use someting like相反,我使用类似的东西

 lngLast = cells(rows.count,3).end(xlUp).row

The following VBA code should get you started.以下 VBA 代码应该可以帮助您入门。 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.它将原始工作簿中的所有数据复制到一个新工作簿,但它会为每个值添加 1,并且所有空白单元格都将被忽略。

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

If you are looking for the last row of a column, use:如果您正在查找列的最后一行,请使用:

Sub SelectFirstColumn()
   SelectEntireColumn (1)
End Sub

Sub SelectSecondColumn()
    SelectEntireColumn (2)
End Sub

Sub SelectEntireColumn(columnNumber)
    Dim LastRow
    Sheets("sheet1").Select
    LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row

    ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub

Other commands you will need to get familiar with are copy and paste commands:您需要熟悉的其他命令是复制和粘贴命令:

Sub CopyOneToTwo()
    SelectEntireColumn (1)
    Selection.Copy

    Sheets("sheet1").Select
    ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub

Finally, you can reference worksheets in other workbooks by using the following syntax:最后,您可以使用以下语法引用其他工作簿中的工作表:

Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")

For me the best way to proceed was to:对我来说,最好的方法是:

  1. Create a new Excel Table创建一个新的 Excel 表
  2. AutoFilter it by the parameter Criterial:="<>"通过参数Criterial:="<>" AutoFilter

An example of the code would be:代码示例如下:

Sub ExampleFilterCol()
    ' Create a Table
    Dim ws As Worksheet
    Dim rg As Range
    Set ws = ActiveSheet
    Set rg = ws.Range("A1").CurrentRegion
    ws.ListObjects.Add(xlSrcRange, rg, , xlYes).Name = "myNonRepeatedTableName"

    ' Filter the created table
    Dim Io As ListObject
    Dim iCol As Long
    ' Set reference to the first Table on the sheet 
    ' That should be the recently created one
    Set lo = Sheets("Totalinfo").ListObjects(1)
    ' Set filter field
    iCol = lo.ListColumns("yourColumnNameToFilter").Index
    ' Non-blank cells – use NOT operator <>
    lo.Range.AutoFilter Field:=iCol, Criteria1:="<>"
End Sub

This might be completely off base, but can't you just copy the whole column into a new spreadsheet and then sort the column?这可能完全不合时宜,但您不能将整列复制到新的电子表格中然后对列进行排序吗? I'm assuming that you don't need to maintain the order integrity.我假设您不需要维护订单的完整性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM