我正在尝试使用 Excel 创建格式化的 INI 文件。
假设我有一列 IP 地址。我希望将该列导出到 INI 文件,并在 IP 地址之前和之后添加文本。
我的 INI 文件应该类似于:
[Transfer-List]
Status=Inactive
CountStation=255
Station1=XXX.XXX.XXX.XXX;VKDGenerator
Station2=YYY.YYY.YYY.YYY;VKDGenerator
Station3=ZZZ.ZZZ.ZZZ.ZZZ;VKDGenerator
Station4=AAA.AAA.AAA.AAA;VKDGenerator
Station5=...
...
...
由于我想创建一个 INI 文件,因此前三行、Station n° 和 VKDGenerator 是必需的。
单元格包含以下公式:
=IFERROR(INDEX(_DATA!$B$2:$F$2685;_DATA!$I15;COLUMN(Generator!$K$3:K16));"")
打开文件进行输出,然后扫描电子表格并打印每一行。
Option Explicit
Sub CreateINI()
Const SUFFIX = ";VKDGenerator"
Const ININAME = "Filename.INI"
Const ROW_START = "3"
Const COL_IP = "K"
Dim cel As Range, rngIP As Range
Dim n As Long, i As Long, ini As String, ff
'open text file
ini = ThisWorkbook.Path & Application.PathSeparator & ININAME
ff = FreeFile
Open ini For Output As #ff
With ThisWorkbook.Sheets("Sheet1")
' number of lines on sheet
n = .Cells(.Rows.Count, COL_IP).End(xlUp).Row
If n < ROW_START Then
MsgBox "No data in column " & COL_IP, vbCritical
End If
' visible rows
Set rngIP = .Cells(ROW_START, COL_IP)
If n > ROW_START Then
Set rngIP = rngIP.Resize(n - ROW_START + 1, 1).SpecialCells(xlVisible)
End If
n = rngIP.Cells.Count
' header
Print #ff, "[Transfer-List]" & vbCrLf & _
"Status=Inactive" & vbCrLf & _
"CountStation=" & n
' stations
For Each cel In rngIP
i = i + 1
Print #ff, "Station" & i & "=" & cel.Text & SUFFIX
Next
End With
Close #ff
MsgBox n + 3 & " lines written to " & ini, vbInformation
' open notepad++
Call Shell("C:\Program Files\Notepad++\notepad++.exe " & ini, 1)
End Sub
在以下代码中找到了解决方案:
Sub ExportToIniFile()
Dim lastRow As Long
Dim iniContent As String
Dim i As Long
' Find the last row in column K starting from row 3
lastRow = Cells(Rows.Count, "K").End(xlUp).Row
' Initialize the INI file content
iniContent = "[Transfer-List]" & vbCrLf & "Status=Inactive" & vbCrLf
' Loop through column K starting from row 3 and add stations to the INI content
For i = 3 To lastRow
iniContent = iniContent & "Station" & (i - 2) & "=" & Cells(i, 11).Value & ";VKDGenerator" & vbCrLf
Next i
' Save the INI file
SaveIniFile iniContent
End Sub
Sub SaveIniFile(content As String)
Dim filePath As String
' Specify the file path where you want to save the INI file
filePath = "C:\Users\PBurri\Documents\Miniinst.ini"
' Open a text file for writing
Open filePath For Output As #1
' Write the content to the file
Print #1, content
' Close the file
Close #1
End Sub
感谢 CDP1802 的指点和代码。 我现在已经有了我想要的 .ini 文件。
我遇到了 ThisWorkbook.Path 的问题,不想在 OneDrive 上写入,并且由于我无法解释的原因,使用复制和粘贴。