添加文件链接,使用Split()分隔文件名-错误:未设置对象变量或带有块变量

时间:2019-07-16 13:38:39

标签: excel vba

我正在编写一个程序,它执行许多不同的任务,并以此为契机进一步熟悉VBA。现在,此代码位于一个单独的文件中,直到获得扎实的代码基础,然后将所做的更改迁移到该文件的实际文件中。

总结我要做什么:

在其中包含使用以下命名结构的文件的文件夹:“ SOP-JV-001-CHL-通道字母的字母锁定-EN”

使用“-”作为分隔符分隔文件名

windowDf = valAndTopicDf.groupBy(
  window(valAndTopicDf.current_timestamp, "3 minutes" ,"2 minutes"),
  #valAndTopicDf.timestamp,
  valAndTopicDf.macID,
  valAndTopicDf.packetType,
  #valAndTopicDf.seqNo
).count()

print(windowDf.columns)

def tracker(df):
  print("*"*50)
  print(df)
  print("*"*50)


query = windowDf \
  .toDF("current_timestamp","macID","packetType","count") \
  .writeStream \
  .outputMode("complete") \
  .format("console") \
  .option("truncate", "false") \
  .start()

query.awaitTermination()

好吧,出现错误:类型不匹配...我之前使用过split语句。太近了!

2 个答案:

答案 0 :(得分:2)

如果以后不使用

Set rngSOPID = Range(Cells(i + 1, 1), Cells(i + 1, 1)),则不是完全需要。通常,VBA提供了一种很好的方式来引用带有Worksheets(Cells(row,column)的单元格。

以下代码循环遍历文件夹中的文件,并将其名称写在第一列中。然后,如果名称由4个以上的-组成,则将它们记在下几列中:

Sub GenerateFileLinks()

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder("C:\Users\putSomePath\")

    Dim i As Long: i = 1

    For Each objFile In objFolder.Files
        With Worksheets(1)
            .Cells(i, 1) = objFile
            If UBound(Split(objFile, "-")) > 3 Then
                .Cells(i, 2) = Split(objFile, "-")(0)
                .Cells(i, 3) = Split(objFile, "-")(1)
                .Cells(i, 4) = Split(objFile, "-")(2)
                .Cells(i, 5) = Split(objFile, "-")(3)
            End If
        End With
        i = i + 1
    Next objFile

End Sub

答案 1 :(得分:1)

  • 您的代码缺少用于拆分文件名的部分。
  • 您不必使用Range,因为Cells(x,y)是一个Range。
  • 您不需要.Select,但应更改单元格的.Value。
  • 我认为您的注释是多余的,因为变量名具有很强的描述性。

尝试一下:

Sub GenerateFileLinks()
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim i As Integer

    'Create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    'Get the folder object
    Set objFolder = objFSO.GetFolder("C:\Users\jbishop\Desktop\SOPs With New Names")

    i = 1

    Dim rngSOPID As Range
    Dim rngDeptCode As Range
    Dim rngURL As Range
    Dim rngLang As Range
    'Loop through each file in the directory

    For Each objFile In objFolder.Files
        Dim varParts As Variant: varParts = Split(objFile.Name, "-")

        Set rngSOPID = Cells(i + 1, 1)
        rngSOPID.Value = varParts(2)

        Set rngDeptCode = Cells(i + 1, 2)
        rngDeptCode.Value = varParts(3)

        Set rngURL = Cells(i + 1, 3)
        rngURL.Value = varParts(4)
        ActiveSheet.Hyperlinks.Add Anchor:=rngURL, Address:=objFile.Path, TextToDisplay:=objFile.Name

        Set rngLang = Cells(i + 1, 4)
        rngLang.Value = varParts(5)

        i = i + 1
    Next objFile
End Sub