Files
vba/src/module/Generic_Master_Common.bas
2026-04-15 19:15:26 +09:00

87 lines
2.9 KiB
QBasic

' ============================================================
' Generic Master Common Functions
' ============================================================
Sub Generic_Master_Import(ByVal ws As Worksheet, ByVal expectedColumnCount As Long)
On Error GoTo ErrorHandler
' Step 1: Select CSV file
Dim filePath As String: filePath = SelectCSVFile()
If filePath = "" Then Exit Sub
' Step 2: Read CSV and return 2D array
Dim lines As Variant: lines = ReadCSVAs2DArrayStrict(filePath, expectedColumnCount, "utf-8")
' Step 3: Clear data rows
Call Generic_ClearDataRows(ws, 7, 3)
' Step 4: Import data
Dim i As Long
Dim writeRow As Long: writeRow = 7
For i = LBound(lines, 1) To UBound(lines, 1)
If Not isRowEmpty Then
Dim colOffset As Long
For colOffset = 1 To expectedColumnCount
ws.Cells(writeRow, 2 + colOffset).Value = CleanCSVField(CStr(lines(i, colOffset)))
writeRow = writeRow + 1
Next colOffset
End If
Next i
MsgBox writeRow - 7 & " rows imported.", vbInformation
Exit Sub
ErrorHandler:
MsgBox "Import fails:" & vbCrLf & Err.Description, vbCritical
End Sub
Sub Generic_Master_Export(ByVal ws As Worksheet, ByVal expectedColumnCount As Long, ByVal lastDataRow As Long)
Dim savePath As String: savePath = GetSaveCSVPath()
If savePath = "" Then Exit Sub
' Count valid rows first (C column non-empty from row 7 onward)
Dim rowCount As Long: rowCount = 0
Dim r As Long
For r = 7 To lastDataRow
If Len(Trim(ws.Cells(r, 3).Value & "")) > 0 Then
rowCount = rowCount + 1
End If
Next r
' If no data, exit
If rowCount = 0 Then
MsgBox "No data rows to output.", vbExclamation
Exit Sub
End If
' Initialize 2D array: (1 To rowCount, 1 To expectedColumnCount) for columns C-I (3 to expectedColumnCount + 2)
Dim dataArray() As Variant
ReDim dataArray(1 To rowCount, 1 To expectedColumnCount)
' Fill the array
Dim dataIdx As Long: dataIdx = 0
Dim j As Long
For r = 7 To lastDataRow
If Len(Trim(ws.Cells(r, 3).Value & "")) > 0 Then
dataIdx = dataIdx + 1
For j = 3 To expectedColumnCount + 2
dataArray(dataIdx, j - 2) = ws.Cells(r, j).Value ' C->1, D->2, ..., I->7
Next j
End If
Next r
' Write using the new array-based CSV writer
Call WriteCSVFromArray(savePath, dataArray, "utf-8", True)
MsgBox "CSV export completed. Total data rows: " & rowCount, vbInformation
End Sub
Sub Generic_ClearDataRows(ByVal ws As Worksheet, ByVal startRow As Long, ByVal columnNum As Long)
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, columnNum).End(xlUp).Row
If lastRow >= startRow Then
ws.Range(ws.Cells(startRow, 1), ws.Cells(lastRow, 20)).ClearContents
End If
End Sub