【发布时间】:2023-04-10 07:27:01
【问题描述】:
所以我有一个部分填充字符数组的 excel 文档(“|”显示 excel 列行):
当前结果(“_”是空格):
1111GGH80100022190
1112QQH80100023201
1113GGH80100045201
1114AAH80100025190
所以我当前的代码输出了上面的结果。问题是字符 1-5 和 21-24 会被跳过。一般来说,如果没有列号,我应该打印“”(空格)。
期望的结果(“_”是一个空格):
_____1111GGH80100022____190
_____1112QQH80100023____201
_____1113GGH80100045____201
_____1114AAH80100025____190
是否有列方法来检测我是否缺少标题列中的范围?我目前使用这个并且只选择数据:
Private Sub WriteFile_Click()
Dim myFile As String, rng As Range, cellValue As Variant, I As Integer, j As Integer
myFile = "C:\Reformatted.txt"
Set rng = Selection
Open myFile For Output As #1
For I = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = cellValue + CStr(rng.Cells(I, j).Value)
cellValue = Replace(cellValue, "NULL", " ")
If j = rng.Columns.Count Then
Print #1, cellValue
End If
Next j
cellValue = ""
Next I
Close #1
Shell "C:\Windows\Notepad.exe C:\Reformatted.txt", 1
End Sub
------------------在TMh885回答之后--------------- ------------------
所以代码可以完美运行,除非您的标题是单个数字“63”
所以我正在尝试这个:
Private Sub CommandButton1_Click()
Dim myFile As String, rng As Range, cellValue As Variant, I As Integer, j As Integer
myFile = "C:\Reformatted.txt"
Set rng = Selection
Open myFile For Output As #1
Dim strArr(1 To 63) As String, intBeg As Integer, intEnd As Integer, intCount As Integer
For I = 2 To rng.Rows.Count
For j = 1 To rng.Columns.Count
If Len(Cells) = 1 Then
cellValue = cellValue + " "
Else
intBeg = Val(Left(Cells(1, j).Value, InStr(1, Cells(1, j).Value, "-") - 1))
intEnd = Val(Right(Cells(1, j).Value, Len(Cells(1, j).Value) - InStr(1, Cells(1, j).Value, "-")))
intCount = 1
For t = intBeg To intEnd
strArr(t) = Mid(Cells(I, j).Value, intCount, 1)
intCount = intCount + 1
Next t
End If
Next j
For t = 1 To UBound(strArr)
If strArr(t) = "" Then strArr(t) = " "
cellValue = cellValue + strArr(t)
Next t
Erase strArr
Print #1, cellValue
cellValue = ""
Next I
Close #1
Shell "C:\Windows\Notepad.exe C:\Reformatted.txt", 1
End Sub
--------------------------------错误快照------------- ---------------------
输入:
【问题讨论】:
-
是否可以假设标题中的每个数字对应一个字符?
-
你能澄清你问题的开头吗?我在您写的内容中没有看到字符 1-5。我完全不明白你要做什么。
-
@DavidGM 和 TMH885 为了清晰起见,我添加了屏幕截图和更全面的结果。再次感谢您的时间!
-
我想我明白你想要做什么。我只是不明白问题是什么。跳过1-5是什么意思?另外这句话是什么意思:是否有列方法来检测我是否在标题列中缺少范围?
-
@TMH8885 和 DavidGM 我澄清了当前和期望的结果。
标签: excel printing header mapping vba