完全公开,我不是编码员。我可以阅读和操作代码,但我从不从头开始编写。
我正在创建一个 Excel 盘点表,该表输出一个 txt 文件以导入到我们公司的库存系统中。
我有一段 VBA 代码,它从 A 列和 C 列获取数据并将其写入 .txt 文件。 该代码在 C 列中查找数据,如果它的值为 0 或更大,则应将值写入 A 列中,并用 a 分隔,并将值写入 C 列中。
c 列中的某些单元格具有 0 值,有些单元格具有计算正确值的公式。
目前,该代码可以正常工作,只是它会忽略值为 0 的单元格,而且它不会停在 C 列中包含数据的最后一个单元格,它会在 txt 文件中将倒数第二行指定为 0,0。
Private Sub Select_Visible_Rows()
On Error Resume Next ' Enable error handling
Application.ScreenUpdating = False
Dim a As Long, i As Long
Dim b As Long, c As Long
Dim wsOrder As Worksheet, wsImport As Worksheet
Dim outputFile As Object
Set wsOrder = ThisWorkbook.Worksheets("Order Sheet")
Set wsImport = ThisWorkbook.Worksheets("IQ Import Sheet")
a = wsOrder.Cells(wsOrder.Rows.Count, 1).End(x1Up).Row
' Create a FileSystemObject to work with files
Set outputFile = CreateObject("Scripting.FileSystemObject").CreateTextFile("C:\Stocktake\Stocktake " & Format(Now(), "DD-MM-YYYY") & ".txt")
Dim lastRow As Long
lastRow = wsOrder.Cells(wsOrder.Rows.Count, 3).End(xlUp).Row
For i = 3 To lastRow
If IsNumeric(wsOrder.Cells(i, 3).Value) And wsOrder.Cells(i, 3).Value >= 0 Then
' Check if Column A is not blank
If Len(Trim(wsOrder.Cells(i, 1).Text)) > 0 And Not (wsOrder.Cells(i, 3).Text Like "=*") Then
' Write data to the text file, separated by commas
outputFile.Write wsOrder.Cells(i, 1).Value & ","
outputFile.WriteLine wsOrder.Cells(i, 3).Value
End If
End If
Next
' Close the text file
outputFile.Close
Application.ScreenUpdating = True
Application.CutCopyMode = False
ActiveWorkbook.Save
ThisWorkbook.Worksheets("IQ Import Sheet").Cells(1, 1).Select
On Error GoTo 0 ' Disable error handling
End Sub
我尝试了很多组合,并尝试使用 chatGPT 来协助,但我似乎无法做到正确。
我只需要 txt 文件来为我提供 A 列(产品代码)中的数据输出,并与 C 列(数量)中的值以逗号分隔。即使值为 0
尝试以下更改:
删除了
Not (wsOrder.Cells(i, 3).Text Like "=*")
ThisWorkbook.Save
而不是 ActiveWorkbook.Save
,因为我没有看到任何其他工作簿被使用,并在激活导入表并选择 A1 后将其放置。如果我错过了什么,请告诉我:)
Private Sub Select_Visible_Rows()
Application.ScreenUpdating = False
Dim i As Long
Dim wsOrder As Worksheet, wsImport As Worksheet
Dim outputFile As Object
Set wsOrder = ThisWorkbook.Worksheets("Order Sheet")
Set wsImport = ThisWorkbook.Worksheets("IQ Import Sheet")
' Create a FileSystemObject to work with files
Set outputFile = CreateObject("Scripting.FileSystemObject").CreateTextFile("Q:\Aankoop\Werkfiles Excel\Steven\Test\Stocktake " & Format(Now(), "DD-MM-YYYY") & ".txt")
Dim lastRow As Long
lastRow = wsOrder.Cells(wsOrder.Rows.Count, 3).End(xlUp).Row
Dim cVal, aVal
For i = 3 To lastRow
cVal = wsOrder.Cells(i, 3).Value
aVal = wsOrder.Cells(i, 1).Value
If Not IsError(cVal) Then
If Len(cVal) > 0 And IsNumeric(cVal) And cVal >= 0 Then
' Check if Column A is not blank
If Len(Trim(aVal)) > 0 Then
' Write data to the text file, separated by commas
outputFile.Write aVal & ","
outputFile.WriteLine cVal
End If
End If
End If
Next
' Close the text file
outputFile.Close
Application.ScreenUpdating = True
wsImport.Activate
wsImport.Cells(1, 1).Select
ThisWorkbook.Save
End Sub
顺便说一句,IsNumeric 会将空单元格视为 0,因此无论如何您都会进入这些 If。因此需要检查其长度。