Vba Excel:如果列中有数字,则返回上下两个空格的单元格和上下两个空格的单元格,输出到单独的文件

Vba Excel:如果列中有数字,则返回上下两个空格的单元格和上下两个空格的单元格,输出到单独的文件,vba,excel,Vba,Excel,不确定这是否可以通过宏或其他方式实现,但是 如果我有一个电子表格,其中数字存在于B列(第一个条目在B7),我想返回D列中与它完全对齐的所有值,并在下面返回一个值(在本例中是D7和D8) 有没有一种方法可以使用宏将这些数据写入文本文件并以这种格式保存 D7,D8 D14,D15 D21,D22 这是我的尝试。您选择了B列中的所有值。我在您的帖子中使用了很多假设,比如需要带过来的值在B列中有一个相应的数值: Sub getDataforFile() Dim objFSO As Object Di

不确定这是否可以通过宏或其他方式实现,但是

如果我有一个电子表格,其中数字存在于B列(第一个条目在B7),我想返回D列中与它完全对齐的所有值,并在下面返回一个值(在本例中是D7和D8)

有没有一种方法可以使用宏将这些数据写入文本文件并以这种格式保存

D7,D8
D14,D15
D21,D22

这是我的尝试。您选择了B列中的所有值。我在您的帖子中使用了很多假设,比如需要带过来的值在B列中有一个相应的数值:

Sub getDataforFile()

Dim objFSO As Object
Dim objFile As Object
Dim filePath As String
Dim myRange As Range
Dim myCell As Range

Set objFSO = CreateObject("Scripting.FileSystemObject")

'this assigns your selection, everything on Colum B to a Range variable
Set myRange = Selection 

filePath = "C:\Output.txt" 'put your own path
Set objFile = objFSO.CreateTextFile(filePath)

For Each myCell In myRange

'if the value in Column B is a number and not an empty string
If IsNumeric(myCell.Value) And Not myCell.Value = "" Then     

'write to the text file, first moving two columns over to the right,
'no rows down, concatenating a comma, and then again moving two columns
'right, one row down, all from the original range, on Column B
    objFile.writeline myCell.Offset(0, 2).Value & ", " & myCell.Offset(1, 2).Value

End If

'continue checking each cell in the selection
Next myCell

objFile.Close

Set objFile = Nothing
Set objFSO = Nothing

End Sub

嗯。这段代码对我来说很有意义,但由于某种原因,我在尝试时遇到了“运行时错误'5':过程调用或参数无效”。调试器将我指向这一行:
objFile.writeline myCell.Offset(0,2).Value&“,”&myCell.Offset(1,2).Value
我认为这不是问题所在,但在引用中添加Windows脚本主机对象模型可能会有所帮助。解决了问题。我的文本是亚洲字符,所以VBA没有接收它。不过,您的代码工作得很好,谢谢!很酷,很高兴知道这有帮助。你介意把这个标记为已回答吗?