使用部分名称从路径打开文件

时间:2020-07-06 13:18:53

标签: excel vba

我找到了从路径(指的是单元格)中打开文件的代码,以及在未知完整文件名时如何打开文件的代码,但是,我无法同时执行这两个操作。这可能吗?

从路径打开文件:

class SearchViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
//    private val searchResults: MutableLiveData<Array<GoodreadsBook>> by lazy {
////        MutableLiveData<Array<GoodreadsBook>>();
////    }

    companion object {
        private const val SEARCH_RESULTS = "searchResults"
    }

    fun getSearchResults(): LiveData<Array<GoodreadsBook>> =
        savedStateHandle.getLiveData<Array<GoodreadsBook>>(SEARCH_RESULTS)


    //    TODO: Add pagination
    fun search(query: String?) {
        val searchResults = savedStateHandle.getLiveData<Array<GoodreadsBook>>(SEARCH_RESULTS)
        if (searchResults.value == null)
            viewModelScope.launch {
                withContext(Dispatchers.Default) {
                    //Handle the API response
                    val callback: Callback = object : Callback {
                        override fun onFailure(call: Call, e: IOException) {
//                TODO: Display error message
                        }

                        override fun onResponse(call: Call, response: Response) {
                            //                TODO: Check res status

                            val gson = Gson();
                            val parsedRes = gson.fromJson(
                                response.body?.charStream(),
                                Array<GoodreadsBook>::class.java
                            );

                            searchResults.postValue(parsedRes)
                        }


                    }
                    launch { searchBook(query, callback) }

                }
            }
    }
}

使用部分名称打开文件(因为它每月更改一次):

searchBook

奇怪的是,部分文件打开代码两次都需要目录,这在遇到此问题并经过思考后很奇怪,对吧?

我假设有一种方法可以做到,但是我似乎无法做到/找到它。

谢谢!

1 个答案:

答案 0 :(得分:1)

我唯一想到的就是遍历指定的文件夹,并检查文件名是否包含所需的月份文本。请参见下面的代码(未经测试,但应指向正确的方向)。

Option Explicit

Sub Open_File()
    
    Dim fs As Object, sf As Object, file As Variant
    Dim sFileName As String
    
    
    Set fs = CreateObject("Scripting.FileSystemObject")
    
    Set sf = fs.GetFolder("C:\Users\tom\Desktop\")
    
    sFileName = "Analytics Google Ads Revenue - Monthly"
    
    For Each file In sf.Files
        If InStr(file.Name, sFileName) > 0 Then
            
            'file found - now execute open method
            
            Exit For
        End If
    Next file
    
End Sub