我剛開始深入VBA,遇到了一些障礙。用VBA在Excel中選擇非空白單元格
我有一張包含50多列,900多行數據的工作表。我需要重新格式化這些列中的10列,並將它們粘貼到新的工作簿中。
如何以編程方式選擇book1列中的每個非空白單元格,通過一些函數運行它,並將結果放入book2中?
我剛開始深入VBA,遇到了一些障礙。用VBA在Excel中選擇非空白單元格
我有一張包含50多列,900多行數據的工作表。我需要重新格式化這些列中的10列,並將它們粘貼到新的工作簿中。
如何以編程方式選擇book1列中的每個非空白單元格,通過一些函數運行它,並將結果放入book2中?
以下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
當我嘗試運行此代碼時,出現一個消息框,提示「Object required」。 – 2009-10-20 19:28:31
如果您正在尋找一列的最後一行,使用方法:
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")
這可能是完全關閉基地,但你就不能整列複製到新的電子表格,然後排序的列?我假設你不需要維護訂單的完整性。
我知道我是很晚了這一點,但這裏的一些有用的樣本:
'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
您正在使用哪個程序:Excel或Access?你的問題標題說Excel,但你的標籤說Access。 – 2009-05-04 19:03:05
肯定Excel,謝謝你指出。這就是爲什麼你不急於標記。 – 2009-05-05 00:53:28