我正在尝试让VBA保存一个依赖于9位数字中前三个序列号的文件。数字看起来像这样:400-134004。我需要制作三个不同的文件,具体取决于第一个数字序列,它们是400,401,402。我该怎么做,或者我的代码出了什么问题。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim String_1 As String
Dim String_2 As String
Dim String_3 As String
String_1 = "400"
String_2 = "401"
String_2 = "402"
If Not Range("A1").Value = "" And Not Range("B1").Value = "" And Not Range("C1").Value = "" Then
If Left(String_1, 3).Range("C1").Select Then
'400 = 312B
ActiveCell.Offset(-1, 0).Range("A1:C1").Select
Selection.Copy
Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = Fa
ActiveWorkbook.SaveAs Filename:="u:\CSV\Diepunch400.csv", FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Save
ActiveWindow.Close (SaveChange = False)
Else
End If
If Left(String_2, 3).Range("C1").Select Then
'401 = 312HTG
ActiveCell.Offset(-1, 0).Range("A1:C1").Select
Selection.Copy
Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = Fa
ActiveWorkbook.SaveAs Filename:="u:\CSV\Diepunch401.csv", FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Save
ActiveWindow.Close (SaveChange = False)
Else
End If
If Left(String_3, 3).Range("C1").Select Then
'402 = 312HTX
ActiveCell.Offset(-1, 0).Range("A1:C1").Select
Selection.Copy
Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = Fa
ActiveWorkbook.SaveAs Filename:="u:\CSV\Diepunch402.csv", FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Save
ActiveWindow.Close (SaveChange = False)
Else
End If
Else
End If
End Sub
答案 0 :(得分:2)
尝试这样的事情:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim String_1 As String
Dim String_2 As String
Dim String_3 As String
String_1 = "400"
String_2 = "401"
String_3 = "402"
If Len(Range("A1").Value) > 0 And Len(Range("B1").Value) > 0 And Len(Range("C1").Value) > 0 Then
Dim sComp as String
sComp = Left(Range("C1"),3)
If sComp = String_1 or sComp = String_2 or sComp = String_3 Then
Range("A1:C1").Copy
Dim wbCopy as Workbook
Set wbCopy = Workbooks.Add
With wbCopy
.Sheets(1).Range("A1").PasteSpecial xlPasteValues
.SaveAs Filename:="u:\CSV\Diepunch" & sComp & ".csv", FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
End If
End If
End Sub