我在作業表上有一個資料欄位作為自定義數字格式
geo: [![![資料列示例][1]][1]
sum:[![![資料列示例][2]][2]
我正在將該欄位與另一個作業表上的其他欄位進行比較,以確定該欄位是否介于兩者之間。所以我得到了下面的代碼,它使用陣列的變體并沿空格分割。我認為最好的方法是使用帶有不等式的datevalueandtimevalue函式,這兩個函式都帶字串。任何想法為什么我在拆分時遇到型別不匹配錯誤?
更新:基于 #### 注釋和列參考錯誤,我自動調整了 dateTime co 并更改了列參考。現在我的sumfull字串獲取列的文本。我仍然在下一行收到型別匹配錯誤。我已經更新了下面的代碼。sumsplit = Split(sumfull, " ")代碼因型別不匹配錯誤而中斷。內容.Cells(i.row, 4).text是“01/23/2022 18:53”。這也是 sumfill 中斷時的值。
Option Explicit
Sub O_face()
Dim geo As Workbook
Dim sum As Workbook
Dim geowks As Worksheet
Dim sumwks As Worksheet
Dim i As Variant
Dim j As Variant
Dim lastrow As Long
Dim georng As Range
Dim sumrng As Range
Dim geofull As Date
Dim sumfull As Date
Dim sumfull2 As Date
Set geo = ThisWorkbook
Set sum = Workbooks.Open("MyFile.csv")
Set geowks = geo.Workshets(1)
geowks.Range("B:B").EntireColumn.AutoFit
Set sumwks = sum.Worksheets(1)
sumwks.Range("F:G").EntireColumn.AutoFit
lastrow = geowks.Cells(Rows.Count, "a").End(xlUp).Row
geowks.AutoFilterMode = False
geowks.Range("A1:L" & lastrow).AutoFilter Field:=5, Criteria1:="<>", Operator:=xlFilterValues
Set georng = geowks.Range("E2:E" & lastrow).SpecialCells(xlCellTypeVisible)
lastrow = sumwks.Cells(Rows.Count, "a").End(xlUp).Row
sumwks.AutoFilterMode = False
sumwks.Range("A1:P" & lastrow).AutoFilter Field:=3, Criteria1:="<>", Operator:=xlFilterValues
Set sumrng = sumwks.Range("C2:C" & lastrow).SpecialCells(xlCellTypeVisible)
'have to split the date time cell because it's a custome data type in the worksheet. Then compare the date and time seperately.....
For i = 1 To sumrng.Rows.Count
sumfull = sumrng.Cells(i, 4)
sumfull2 = sumrng.Cells(i, 5)
For j = 1 To georng.Rows.Count
geofull = georng.Cells(j, -2)
If sumrng(i, 1) = georng(j, 1) And _
geofull >= sumfull And geofull >= sumfull2 Then
sumrng.Cells(i, 15) = "IS THIS WHAT YOU WANT!!!!"
End If
End If
Next j
Next i
End Sub
uj5u.com熱心網友回復:
(a)
Split回傳一個字串陣列。您可以將結果分配給動態字串陣列或變體變數,請參閱https://stackoverflow.com/a/57113178/7599798。您嘗試做的是將其分配給 Variant Array - 這將失敗。您也不需要設定該陣列的尺寸split,無論如何都會注意這一點。所以那將是:
Dim sumsplit() As String
sumfull = CStr(sumrng.Cells(i.Row, "f").Text)
sumsplit = Split(sumfull)
(b) 假設您在 Excel 中的資料是日期(不是看起來像日期的字串),沒有理由將它們轉換為字串,也沒有理由拆分該字串來獲取日期和時間部分。只需使用日期變數。在后臺,日期是浮點數(=雙)。小數點前的數字定義日期部分(自 31.12.1899 以來的天數),其余為時間。要獲取 Excel 日期的日期和時間:
Dim sumfull As Date, fsumdate As Date, fsumtime As Date
sumfull = sumrng.Cells(i.Row, "f").value
fsumdate = int(sumfull) ' Remove the digits after the decimal
fsumtime = sumFull-int(sumfull) ' The digits after the decimal is the Time.
(c)我不完全理解您的 If 陳述句的邏輯,但您可以簡單地將日期變數與<and進行比較>- 較高的數字意味著較晚的日期/時間。我假設您不需要分別比較日期和時間部分。可能會這樣做:
Dim geoDate As Date, fsumDate As Date, lSumDate As Date
fsumDate = sumrng.Cells(i.Row, "f").value
lsumDate = sumrng.Cells(i.Row, "g").value
geoDate = georng.Cells(j.Row, "b").value
If geodate >= fsumdate And geodate <= lsumdate Then
(d)
通常,您應該避免使用Text-property。如果由于某種原因單元格的寬度太小而無法顯示日期,Excel 將改為顯示“######” - 您將在程式中得到準確的資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441753.html
