programing

VBA를 사용하여 Excel에서 비어 있지 않은 셀 선택

muds 2023. 8. 14. 23:11
반응형

VBA를 사용하여 Excel에서 비어 있지 않은 셀 선택

저는 이제 막 VBA에 뛰어들기 시작했고 약간의 장애물에 부딪혔습니다.

50개 이상의 열과 900개 이상의 데이터 행이 있는 시트가 있습니다.열 개 정도를 다시 포맷해서 새 워크북에 넣어야 합니다.

book1의 열에서 비어 있지 않은 모든 셀을 프로그래밍 방식으로 선택하고 일부 기능을 실행한 후 book2에 결과를 삭제하려면 어떻게 해야 합니까?

제가 이것에 대해 매우 늦었다는 것을 알지만, 여기 몇 가지 유용한 샘플이 있습니다.

'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

다음 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


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

열의 마지막 행을 찾는 경우 다음을 사용합니다.

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. 새 Excel 테이블 만들기
  2. AutoFilter매개변수에 의한 그것.Criterial:="<>"

코드의 예는 다음과 같습니다.

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

이것은 완전히 기본이 아닐 수도 있지만, 전체 열을 새 스프레드시트로 복사한 다음 열을 정렬할 수는 없습니까?저는 당신이 주문 무결성을 유지할 필요가 없다고 생각합니다.

언급URL : https://stackoverflow.com/questions/821364/selecting-non-blank-cells-in-excel-with-vba

반응형