enter image description here我试图比较宏中的两个变量,但这两个变量将会发生变化。这就是我到目前为止所拥有的:
Selection.End(xlToRight).Select
Dim Year As Integer
Year = ActiveCell.Value
ActiveCell.Offset(-1, 0).Select
Dim Year2 As Integer
Year 2 = ActiveCell.Value
If Year2 <> Year + 1 Then
ActiveCell.Offset(1, 0).Select
ActiveCell.Offset(0, -1).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
End If
好的,基本上这就是我想要做的事情。我已经问了一个关于第一部分的问题,很遗憾重复自己,但这可能会使这个问题变得清晰。本质上,我必须创建一个宏,允许用户选择一个文件并将其上传并附加到工作表的末尾。但是,数据文件按顺序排列,名为&#34; 2015 latest.txt&#34;,&#34; 2016 latest.txt&#34;,&#34; 2017 latest.txt&#34;等我需要如果用户不按顺序上传文件,则停止附加数据的宏。因此,如果上传的最后一个文件是&#34; 2016 latest.txt&#34;他们选择&#34; 2018 latest.txt&#34;我需要删除数据或要阻止的文件一起导入。我无法弄清楚如何操纵宏关于文件的名称(我尝试使用静态变量但是没有工作)。相反,我只是使用数据(因为它列出了年份),并尝试命名两个变量并比较它们,然后删除数据,如果它不匹配。这是我的完整宏:
Option Explicit
Sub ImportTextFile()
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
Dim fName As String, LastRow As Long
fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fName = "False" Then Exit Sub
LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
Destination:=Range("A" & LastRow))
.Name = "sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = True
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
End With
Selection.EntireRow.Delete
Selection.End(xlToRight).Select
Dim Year As Integer
Year = ActiveCell.Value
ActiveCell.Offset(-1, 0).Select
Dim Year2 As Integer
Year2 = ActiveCell.Value
If Year2 <> Year + 1 Then
ActiveCell.Offset(1, 0).Select
ActiveCell.Offset(0, -1).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
End If
End Sub