excel - 文本到列宏故障
问题描述
我正在尝试将此宏用作使用“文本到列”提示的快捷方式。我突出显示有问题的列或垂直单元格组,并且在运行宏时,消息框接受一个字符分隔符。当这三件事都发生时,就会出现问题。
这是我第一次在工作簿中运行宏(如果我再次运行宏,则不会发生故障)
我突出显示一整列
需要解析的第一个单元格上方有空白单元格。
例如,如果我在单元格 D10 中有文本“123-456”,我突出显示所有 D 列并运行由“-”分隔的宏,它将数据解析为 D1 和 E1。如果我删除第 1 行中的信息并再次尝试,除了将数据解析为 D10 和 E10 之外,它仍然有效
不知道如何解决这个问题。
Sub Txt2Clm()
'
' Txt2Clm Macro
'
'
mbox = InputBox("Text-To-Columns", "Quick Step", "Enter Delimiter")
Selection.TextToColumns , DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:=mbox, FieldInfo:=Array(Array(1, 2), Array(2, 2)), TrailingMinusNumbers:=True
End Sub
预期结果应该是 Text to Column 通常的工作方式。
解决方案
试试这个。它包括许多错误检查和数据验证,以确保它只能对有效数据进行 Text-To-Columns:
Sub Txt2Clm()
Dim rValues As Range
Dim rArea As Range
Dim sDelim As String
'Evalute selected range for valid data that can have text to columns performed on it (no blanks, no formulas)
If Selection.Cells.Count = 1 Then
If Selection.HasFormula = False And Len(Selection.Value) > 0 Then Set rValues = Selection
Else
'Only get constant values from first column (text to columns can only work on a single column at a time)
On Error Resume Next
Set rValues = Selection.Resize(, 1).SpecialCells(xlCellTypeConstants)
On Error GoTo 0
End If
If Not rValues Is Nothing Then
'Prompt for delimiter
sDelim = InputBox("Text-To-Columns", "Quick Step", "Enter Delimiter")
If Len(sDelim) = 0 Then Exit Sub 'Pressed cancel
If Len(sDelim) > 1 Then
MsgBox "Delimiter must be a single character"
Exit Sub
End If
Application.DisplayAlerts = False 'Prevent DisplayAlerts to suppress potential "Override existing data?" prompt
For Each rArea In rValues.Areas
rArea.TextToColumns rArea, xlDelimited, xlTextQualifierDoubleQuote, False, Other:=True, OtherChar:=sDelim
Next rArea
Application.DisplayAlerts = True
Else
MsgBox "No cells containing valid data selected."
End If
End Sub
推荐阅读
- python - 为什么在尝试使用 bs4 获取包含 python 中特定类的链接时得到空列表?
- r - R:将每个值与列中的一组先前值进行比较
- wordpress - Wordpres 帖子未在移动版本上加载
- java - 抑制/避免在更高版本的 Android SDK 中创建的类的 java.lang.NoClassDefFoundError
- java - 弹簧模块和弹簧启动器模块之间的区别
- javascript - 在 Google Colab Notebook 中提供 iframe:localhost 拒绝连接
- bash - 包含波浪号的字符串的 grep 返回不匹配的行
- r - 根据条件扩展为宽格式
- python - 在tensorflow v1.13中将张量值分配给占位符
- shell - 使用 sed(1) 的 UNIX 命令行上的 CVS 文件解析器,可以完成吗?