Tyl*_*ash 12 excel vba spreadsheet excel-vba
我刚刚开始潜入VBA,我遇到了一些障碍.
我有一张包含50多列,900多行数据的工作表.我需要重新格式化其中的10个列,并将它们粘贴到新的工作簿中.
如何以编程方式选择book1列中的每个非空单元格,通过某些函数运行它,并将结果放在book2中?
Pat*_*rez 15
我知道我已经很晚了,但这里有一些有用的样本:
'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select
Run Code Online (Sandbox Code Playgroud)
要么
'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
.value = .value
end with
Run Code Online (Sandbox Code Playgroud)
要查找列中最后使用的行,请不要依赖LastCell,这是不可靠的(删除数据后不会重置).相反,我使用像
lngLast = cells(rows.count,3).end(xlUp).row
Run Code Online (Sandbox Code Playgroud)
以下VBA代码应该可以帮助您入门.它会将原始工作簿中的所有数据复制到新工作簿,但它会为每个值添加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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)