2009-05-04 393 views
11

我刚开始深入VBA,遇到了一些障碍。用VBA在Excel中选择非空白单元格

我有一张包含50多列,900多行数据的工作表。我需要重新格式化这些列中的10列,并将它们粘贴到新的工作簿中。

如何以编程方式选择book1列中的每个非空白单元格,通过一些函数运行它,并将结果放入book2中?

+0

您正在使用哪个程序:Excel或Access?你的问题标题说Excel,但你的标签说Access。 – 2009-05-04 19:03:05

+0

肯定Excel,谢谢你指出。这就是为什么你不急于标记。 – 2009-05-05 00:53:28

回答

5

以下VBA co德应该让你开始。它会将原始工作簿中的所有数据复制到新的工作簿中,但它将为每个值添加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 
+0

当我尝试运行此代码时,出现一个消息框,提示“Object required”。 – 2009-10-20 19:28:31

2

如果您正在寻找一列的最后一行,使用方法:

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 

其他命令,你需要熟悉的复制和粘贴命令:

Sub CopyOneToTwo() 
    SelectEntireColumn (1) 
    Selection.Copy 

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

最后,可以使用以下语法引用其他工作簿中的工作表:

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

这可能是完全关闭基地,但你就不能整列复制到新的电子表格,然后排序的列?我假设你不需要维护订单的完整性。

14

我知道我是很晚了这一点,但这里的一些有用的样本:

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

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

要找到上次使用的排列,从不依靠LastCell,这是不可靠的(删除数据后不重置)。相反,我使用类似于

lngLast = cells(rows.count,3).end(xlUp).row 
相关问题