请求协助:实现Excel A列非空行导出为CSV文件的VBA代码优化
Solution: Export Only Rows with Non-Empty Column A to CSV
I've adjusted your VBA code to add the filter for non-empty Column A cells. The key change is adding a check before processing each row to ensure Column A has actual content (not blank, not just whitespace, and not null).
Optimized Code
Sub ExportCSV() Dim Bereich As Object, Zeile As Object, Zelle As Object Dim strTemp As String Dim strDateiname As String Dim strTrennzeichen As String Dim strMappenpfad As String Dim blnAnfuehrungszeichen As Boolean Dim colACell As Object ' Added to reference Column A cell of current row strMappenpfad = ActiveWorkbook.FullName strDateiname = InputBox("Bitte den Namen der CSV-Datei angeben.", "CSV-Export", strMappenpfad) If strDateiname = "" Then Exit Sub strTrennzeichen = InputBox("Welches Trennzeichen soll verwendet werden?", "CSV-Export", ",") If strTrennzeichen = "" Then Exit Sub If MsgBox("Sollen die Werte in Anführungszeichen exportiert werden?", vbQuestion + vbYesNo, "CSV-Export") = vbYes Then blnAnfuehrungszeichen = True Else blnAnfuehrungszeichen = False End If Set Bereich = ActiveSheet.UsedRange Open strDateiname For Output As #1 For Each Zeile In Bereich.Rows ' Get the Column A cell of the current row Set colACell = Zeile.Cells(1) ' Check if Column A cell is NOT empty (exclude whitespace-only cells and nulls) If Not IsEmpty(colACell) And Trim(CStr(colACell.Value)) <> "" Then strTemp = "" ' Reset temp string for valid row For Each Zelle In Zeile.Cells If blnAnfuehrungszeichen = True Then strTemp = strTemp & """" & CStr(Zelle.Text) & """" & strTrennzeichen Else strTemp = strTemp & CStr(Zelle.Text) & strTrennzeichen End If Next ' Remove trailing delimiter and print the row If Right(strTemp, 1) = strTrennzeichen Then strTemp = Left(strTemp, Len(strTemp) - 1) End If Print #1, strTemp End If Next Close #1 Set Bereich = Nothing Set colACell = Nothing MsgBox "Export erfolgreich. Datei wurde exportiert nach" & vbCrLf & strDateiname End Sub
Key Changes Explained
- Added Column A Check: Before processing each row, we check if the Column A cell (
Zeile.Cells(1)) is not empty. TheTrim(CStr(colACell.Value)) <> ""ensures we exclude cells that only contain whitespace, andNot IsEmpty(colACell)handles null/empty cell cases. - Reset Temp String Inside Valid Row Block: Moved
strTemp = ""inside the conditional block to avoid carrying over leftover text from invalid rows. - Cleaned Up Object References: Added
Set colACell = Nothingto properly release memory.
This version will only export rows where Column A has actual content, skipping any rows where Column A is blank, null, or filled with just spaces.
内容的提问来源于stack exchange,提问作者DrNaughtyDog
相关产品推荐
相关产品推荐

