Поиск первой пустой строки, затем запись на нее

Вопрос:Мне нужно найти первую пустую строку в книге и записать информацию в (строка, 1) и (строка, 2). Я думаю, что я в настоящее время довольно застрял... Function WriteToMaster(num, path) As Boolean 'Declare variables Dim xlApp As Excel.Application Dim wb As Workbook Dim ws As Worksheet Dim infoLoc As Integer Set xlApp = New Excel.Application Set

Вопрос:

Мне нужно найти первую пустую строку в книге и записать информацию в (строка, 1) и (строка, 2). Я думаю, что я в настоящее время довольно застрял…

Function WriteToMaster(num, path) As Boolean ‘Declare variables Dim xlApp As Excel.Application Dim wb As Workbook Dim ws As Worksheet Dim infoLoc As Integer Set xlApp = New Excel.Application Set wb = xlApp.Workbooks.Open(«PATH OF THE DOC») Set ws = wb.Worksheets(«Sheet1») ‘Loop through cells, looking for an empty one, and set that to the Num Cells(1, 1).Select For Each Cell In ws.UsedRange.Cells If Cell.Value = «» Then Cell = Num MsgBox «Checking cell » & Cell & » for value.» Next ‘Save, close, and quit wb.Save wb.Close xlApp.Quit ‘Resets the variables Set ws = Nothing Set wb = Nothing Set xlApp = Nothing

Большое спасибо за любую помощь.

Лучший ответ:

Если вы имеете в виду номер строки после последней используемой строки, вы можете найти ее следующим образом:

Dim unusedRow As Long unusedRow = Cells.SpecialCells(xlCellTypeLastCell).Offset(1, 0).Row

Если вы имеете в виду строку, которая после этого становится пустой с данными после нее… она становится более сложной.

Здесь написана функция, которая даст вам фактический номер строки первой строки, пустой для предоставленного рабочего листа.

Function firstBlankRow(ws As Worksheet) As Long ‘returns the row # of the row after the last used row ‘Or the first row with no data in it Dim rw As Range For Each rw In ws.UsedRange.Rows If rw.Address = ws.Range(rw.Address).SpecialCells(xlCellTypeBlanks). _ Address Then firstBlankRow = rw.Row Exit For End If Next If firstBlankRow = 0 Then firstBlankRow = ws.Cells.SpecialCells(xlCellTypeLastCell). _ Offset(1, 0).Row End If End Function

Пример использования: firstblankRow(thisworkbook.Sheets(1)) или передать любой рабочий лист.

Изменить: как указывалось Ooo, это будет ошибка, если в используемом диапазоне нет пустых ячеек.

Ответ №1

Я бы сделал это так. Коротко и ясно:)

Sub test() Dim rngToSearch As Range Dim FirstBlankCell As Range Dim firstEmptyRow As Long Set rngToSearch = Sheet1.Range(«A:A») ‘Check first cell isn’t empty If IsEmpty(rngToSearch.Cells(1, 1)) Then firstEmptyRow = rngToSearch.Cells(1, 1).Row Else Set FirstBlankCell = rngToSearch.FindNext(After:=rngToSearch.Cells(1, 1)) If Not FirstBlankCell Is Nothing Then firstEmptyRow = FirstBlankCell.Row Else ‘no empty cell in range searched End If End If End Sub

Обновлен, чтобы проверить, пуста ли первая строка.

Изменить: обновить, чтобы включить проверку, если целая строка пуста

Option Explicit Sub test() Dim rngToSearch As Range Dim firstblankrownumber As Long Set rngToSearch = Sheet1.Range(«A1:C200») firstblankrownumber = FirstBlankRow(rngToSearch) Debug.Print firstblankrownumber End Sub Function FirstBlankRow(ByVal rngToSearch As Range, Optional activeCell As Range) As Long Dim FirstBlankCell As Range If activeCell Is Nothing Then Set activeCell = rngToSearch.Cells(1, 1) ‘Check first cell isn’t empty If WorksheetFunction.CountA(rngToSearch.Cells(1, 1).EntireRow) = 0 Then FirstBlankRow = rngToSearch.Cells(1, 1).Row Else Set FirstBlankCell = rngToSearch.FindNext(After:=activeCell) If Not FirstBlankCell Is Nothing Then If WorksheetFunction.CountA(FirstBlankCell.EntireRow) = 0 Then FirstBlankRow = FirstBlankCell.Row Else Set activeCell = FirstBlankCell FirstBlankRow = FirstBlankRow(rngToSearch, activeCell) End If Else ‘no empty cell in range searched End If End If End Function Ответ №2

Обновление

Вдохновленный кодексом Дэниела выше и тот факт, что это ПУТЬ! более интересным для меня сейчас, а затем фактической работой, которую я должен сделать, я создал надежную полнофункциональную функцию, чтобы найти первую пустую строку на листе. Усовершенствования приветствуются! В противном случае это пойдет в мою библиотеку:)
Надеюсь, что и другие принесут пользу.

Function firstBlankRow(ws As Worksheet) As Long ‘returns the row # of the row after the last used row ‘Or the first row with no data in it Dim rngSearch As Range, cel As Range With ws Set rngSearch = .UsedRange.Columns(1).Find(«») ‘-> does blank exist in the first column of usedRange If Not rngSearch Is Nothing Then Set rngSearch = .UsedRange.Columns(1).SpecialCells(xlCellTypeBlanks) For Each cel In rngSearch If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then firstBlankRow = cel.Row Exit For End If Next Else ‘-> no blanks in first column of used range If Application.WorksheetFunction.CountA(Cells(.Rows.Count, 1).EntireRow) = 0 Then ‘-> is the last row of the sheet blank? ‘-> yeap!, then no blank rows! MsgBox «Whoa! All rows in sheet are used. No blank rows exist!» Else ‘-> okay, blank row exists firstBlankRow = .UsedRange.SpecialCells(xlCellTypeBlanks).Row + 1 End If End If End With End Function

Оригинальный ответ

Чтобы найти первый пробел в листе, замените эту часть вашего кода:

Cells(1, 1).Select For Each Cell In ws.UsedRange.Cells If Cell.Value = «» Then Cell = Num MsgBox «Checking cell » & Cell & » for value.» Next

С помощью этого кода:

With ws Dim rngBlanks As Range, cel As Range Set rngBlanks = Intersect(.UsedRange, .Columns(1)).Find(«») If Not rngBlanks Is Nothing Then ‘-> make sure blank cell exists in first column of usedrange ‘-> find all blank rows in column A within the used range Set rngBlanks = Intersect(.UsedRange, .Columns(1)).SpecialCells(xlCellTypeBlanks) For Each cel In rngBlanks ‘-> loop through blanks in column A ‘-> do a countA on the entire row, if it 0, there is nothing in the row If Application.WorksheetFunction.CountA(cel.EntireRow) = 0 Then num = cel.Row Exit For End If Next Else num = usedRange.SpecialCells(xlCellTypeLastCell).Offset(1).Row End If End With Ответ №3

Я знаю, что это старый поток, но мне нужно написать функцию, которая вернула первую пустую строку WITHIN диапазона. Весь код, который я нашел в Интернете, фактически просматривает всю строку (даже ячейки вне диапазона) для пустой строки. Данные в диапазонах вне диапазона поиска запускали использованную строку. Это казалось мне простым решением:

Function FirstBlankRow(ByVal rngToSearch As Range) As Long Dim R As Range Dim C As Range Dim RowIsBlank As Boolean For Each R In rngToSearch.Rows RowIsBlank = True For Each C In R.Cells If IsEmpty(C.Value) = False Then RowIsBlank = False Next C If RowIsBlank Then FirstBlankRow = R.Row Exit For End If Next R End Function Ответ №4ActiveSheet.Range(«A10000»).End(xlup).offset(1,0).Select Ответ №5

очень старая нить, но.. я искал “более легкий”… меньший код

Я честно не понимаю ни одного из ответов выше: D
– i’m a noob

но это должно выполнить эту работу. (для небольших листов)

Set objExcel = CreateObject(«Excel.Application») objExcel.Workbooks.Add

читает каждую ячейку в столбце 1 снизу вверх и останавливается в первой пустой ячейке

intRow = 1 Do until objExcel.Cells(intRow, 1).Value = «» intRow = intRow + 1 Loop

тогда вы можете написать свою информацию следующим образом

objExcel.Cells(intRow, 1).Value = «first emtpy row, col 1» objExcel.Cells(intRow, 2).Value = «first emtpy row, col 2»

и т.д.

а затем я узнаю его поток vba… lol

Ответ №6

Очень старая нить, но проще взять:)

Sub firstBlank(c) ‘as letter MsgBox (c & Split(Range(c & «:» & c).Find(«», LookIn:=xlValues).address, «$»)(2)) End Sub Sub firstBlank(c) ‘as number cLet = Split(Cells(1, c).address, «$»)(1) MsgBox (cLet & Split(Range(cLet & «:» & cLet).Find(«», LookIn:=xlValues).address, «$»)(2)) End Sub Ответ №7

Функция firstBlankRow() как долго
  Dim emptyCells As Boolean

For Each rowinC In Sheet7.Range(«A» & currentEmptyRow & «:A5000») ‘ (row,col) If rowinC.Value = «» Then currentEmptyRow = rowinC.row ‘firstBlankRow = rowinC.row ‘define class variable to simplify computing complexity for other functions i.e. no need to call function again Exit Function End If Next

Конечная функция

Оцените статью
Добавить комментарий