VBA Excel:如果数据数组可能不同,如何将CSV数据导入范围

我的macros将从DAQ应用程序保存的CSV数据导入范围A2:AC12。 数据“典型”包括下图D2和D17中的16组数据。 (FYI,我使用A1作为固定标题信息&E2:F17是将0-15设置转换为1-16用于绘图的目的)。

理想CSV数据的例子,16次运行

不过,我说“典型”的原因是因为DAQ应用程序用户可能select不同的运行集或跳过一些运行。 下面是他们执行运行的一个例子,并且跳过了0-4组,并且只select了4-15。 如果我现在将这些数据导入到我的macros中,这就是它的样子。 在这里输入图像说明

你可以在这里看到设置5在D2(其中设置0应该是)的问题。 此外,计算arrays(N21:AC35)会注意到空白并导致DIV / 0错误。 由于我对导入数据的知识有限,因此我使用最基本的代码来简单地将CSV导入到A2中:

'Imports CSV Data With ActiveSheet.QueryTables.Add(Connection:= _ "TEXT;" & myDirString, Destination:=Range("$A$2")) .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .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) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With 

所以主要的问题是如何导入数据(无论是0-15套,5-15套还是2-4-6-8套等),并且仍然按照0-15行? 我应该依赖FOR循环还是IF语句? 我很困惑如何处理这样的大范围的数据,只用于固定的数据运行。

理想情况下,我希望它看起来像这样。 我手动操作数据为例,只需在空的非运行空间中input“n / a”即可: 在这里输入图像说明

阅读你的文章,看看截图,你总是期望A1:A17范围内的东西。 如果是这样,那么你可以在导入macros导入数据后运行这个:

 For i = 2 To 17 If ActiveSheet.Range("d" & i) <> i - 2 Then ActiveSheet.Range(i & ":" & i).Insert shift:=xlShiftDown With ActiveSheet.Range("a" & i & ":ac" & i) .Formula = "=na()" .Value = .Value End With ActiveSheet.Range("d" & i).Value = i - 2 End If Next i 'assuming your button is named 'Button 1' 'if you knew it was always the first shape made on the sheet then 'you could also access the button by index: Shapes(1) with ActiveSheet.Shapes("Button 1") .Left = ActiveSheet.Range("b18").Left .Top = ActiveSheet.Range("b18").Top End With 

编辑

for循环之后添加一个with语句,将button的左上angular放在单元格b18